Search code examples
javajsonrestswingobjectmapper

JSON object array to pojo


When I invoke a REST service (GET) from postman, it retrieves the result. But when tried to consume the service from code, I dont' get the data as expected. I suspect it has something to do with the JSON/POJO mapping. I tried it different ways but does not give the result. What could be possibly wrong here?

enter image description here

Here is my json response when I try from postman

[
  {
    "id": 20,
    "type": 2,
    "data": {
      "name": "car"
    }
  },
  {
   "id": 20,
   "type": 2,
   "data": {
    "name": "car"
    }
  }
]

Here is my pojo:

class Market{
  public int id;
  public int type;
  public MarketData data;
}
class MarketData {
   public Strig name;

}

And here is how I consume the service:

HttpClient client = HttpClients.custom().build();

 HttpUriRequest request = RequestBuilder.get()
         .setUri("url")
         .setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
         .setHeader(HttpHeaders.ACCEPT, "application/json")
         .build();

 HttpResponse response = client.execute(request);
 if (response.getStatusLine().getStatusCode() != 200) {
     throw new RuntimeException("Failed : HTTP error code : "
             + response.getStatusLine().getStatusCode());
 } 
 
 ObjectMapper mapper = new ObjectMapper();
 MarketData[] marketData = mapper.readValue(response.getEntity().getContent(), MarketData[].class);
 

Solution

  • As pointed out in comment by Nico, I think you have a typo on the objectMapper.readValue() line. It should be providing array type for Market, not MarketData. What I mean is this line:

    MarketData[] marketData = mapper.readValue(response.getEntity().getContent(), MarketData[].class);
    

    Should actually be:

    Market[] markets = objectMapper.readValue(response, Market[].class);
    

    I tested this code like this:

    File responseFile = new File(JsonObjectArrayToPojo.class.getResource("/response.json").getFile());
    String response = new String(Files.readAllBytes(responseFile.toPath()));
    ObjectMapper objectMapper = new ObjectMapper();
    Market[] markets = objectMapper.readValue(response, Market[].class);
    
    System.out.println("marketData length " + markets.length);
    for (Market m :  markets) {
        System.out.printf("\tid: %s", m.id);
        System.out.printf("\ttype: %s", m.type);
        System.out.printf("\tdata name: %s", m.data.name);
    
        System.out.println();
    }
    

    I added this response.json to my resource directory:

    [{
        "id": 20, "type": 2, "data": { "name": "car"}
      },
      {
        "id": 10, "type": 1, "data": { "name": "Bike" }
      }]
    

    This prints the following output:

    marketData length 2
        id: 20  type: 2 data name: car
        id: 10  type: 1 data name: Bike