Home > database >  Java how to retrieve a particular field form http response
Java how to retrieve a particular field form http response

Time:11-09

I'm trying to do this by convert the response to json and then find the filed form it.

But I don't know neither how to convert it to json, nor how to traverse the json.

@POST
    @Path("/custoemrs")
    @Produces({ MediaType.APPLICATION_JSON })
    Response createCustomer(Customer customer);

there would be a id field which I want to extract.

There are too many answers out there, I tried some of them but none is working.

I want to use jackson to process the json file, and I'm using resteasy client.

The response I'm using is javax.ws.rs.core.Response, please kindly base on this to answer

I saw many people said something like

EntityUtils.toString(entity)

But I can't even resolve the entityutils...

CodePudding user response:

ObjectMapper is the core class in Jackson, use that. There is no need convert anything to a String, Jackson can read directly from the HTTP input stream.

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.io.InputStream;

public class ParseJSON {
    public static void main(String[] args) throws IOException {
        InputStream streamFromServer = streamFromServer; //Wherever this comes from
        final JsonNode jsonNode = new ObjectMapper().readTree( streamFromServer );
        final String yourValue = jsonNode.at( "/path/to/your/value" ).asText();
    }
}

CodePudding user response:

Though I am not sure how your Customer object looks like but below might be helpful to you:

String customer = EntityUtils.toString(entity);  // returns your customer in String format.
ObjectMapper mapper = new ObjectMapper();  // this is com.fasterxml.jackson.databind.ObjectMapper class

HashMap<?, ?> map = mapper.readValue(customer, HashMap.class);  

System.out.println(map.get("id")); // extracting id field.
  • Related