Swarup Saha
Swarup Saha

Reputation: 995

Parsing JSON Response using Jackson

I have written a web-service and hosted in the following URL http://192.168.2.34:8081/MyWebService/facility/university

Response from this web service in JSON format is:

{
  "university": [
    {
      "emailOfPrincipal": "[email protected]",
      "labLists": [
        {
          "instrumentLists": [
            {
              "instrumentId": "1",
              "instrumentName": "Instrument 1"
            },
            {
              "instrumentId": "2",
              "instrumentName": "instrument 2"
            }
          ],
          "labId": "11",
          "labName": "Lab 11"
        },
        {
          "instrumentLists": [
            {
              "instrumentId": "3",
              "instrumentName": "instrument 3"
            },
            {
              "instrumentId": "4",
              "instrumentName": "instrument 4"
            }
          ],
          "labId": "22",
          "labName": "Lab 22"
        }
      ],
      "univAddress": "Kolkata",
      "univId": "111",
      "univName": "University 111",
      "univPrincipalName": "Principal 1"
    },
    {
      "emailOfPrincipal": "[email protected]",
      "labLists": [
        {
          "instrumentLists": [
            {
              "instrumentId": "5",
              "instrumentName": "Instrument 5"
            },
            {
              "instrumentId": "6",
              "instrumentName": "Instrument 6"
            }
          ],
          "labId": "33",
          "labName": "Lab 33"
        },
        {
          "instrumentLists": [
            {
              "instrumentId": "7",
              "instrumentName": "Instrument 7"
            },
            {
              "instrumentId": "8",
              "instrumentName": "Instrument 8"
            }
          ],
          "labId": "44",
          "labName": "Lab 44"
        }
      ],
      "univAddress": "Bangalore",
      "univId": "222",
      "univName": "University 222",
      "univPrincipalName": "Principal 2"
    },
    {
      "emailOfPrincipal": "[email protected]",
      "labLists": [
        {
          "instrumentLists": [
            {
              "instrumentId": "9",
              "instrumentName": "Instrument 9"
            },
            {
              "instrumentId": "10",
              "instrumentName": "Instrument 10"
            }
          ],
          "labId": "55",
          "labName": "Lab 55"
        },
        {
          "instrumentLists": [
            {
              "instrumentId": "11",
              "instrumentName": "Instrument 11"
            },
            {
              "instrumentId": "12",
              "instrumentName": "Instrument 12"
            }
          ],
          "labId": "66",
          "labName": "Lab 66"
        }
      ],
      "univAddress": "Hyderabad",
      "univId": "333",
      "univName": "University 333",
      "univPrincipalName": "Principal 3"
    }
  ]
}

I am trying to convert JSON data into Java object using jackson api. But getting an error. My Java Objects are:

University.java

public class University {
    private int univId;
    private String univName;
    private String univAddress;
    private String univPrincipalName;
    private String emailOfPrincipal;
    private List<Laboratory> labLists = new ArrayList<>();

    //... Getter and Setter Methods...
}

Laboratory.java

public class Laboratory {

    private int labId;
    private String labName;
    private List<Instruments> instrumentLists = new ArrayList<>();
    //... Getter and Setter Methods...
}

Instruments.java

public class Instruments {

    private int instrumentId;
    private String instrumentName;
    private String bookingStatus;
    private Date bookingFrom;
    private Date bookingTo;
    private Date requestedTime;

    //... Getter and Setter Methods...
}

The Client written is:

public class ParseJSONData {

    public static void main(String[] args) throws ClientProtocolException, IOException {
        String URL = "http://192.168.2.34:8081/MyWebService/facility/university";
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(URL);
        HttpResponse response = httpclient.execute(httpget);
        // System.out.println(response);

        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity);

        ObjectMapper mapper = new ObjectMapper();

        University universities = mapper.readValue(result, University.class);
        System.out.println(universities.getEmailOfPrincipal());
    }

The error I am getting says

Exception in thread "main" org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "university" (Class University), not marked as ignorable
 at [Source: java.io.StringReader@100edc0; line: 1, column: 16] (through reference chain: University["university"])

I know my JSON data is returning List of universities. But how to map those in List I am not aware of. Any sort of help will be greatly appreciated.

Upvotes: 1

Views: 5775

Answers (1)

varren
varren

Reputation: 14741

You can add parent class

public class UniversityList {
    private List<University> university;
    //... Getter and Setter Methods...
}

and us it like this:

ObjectMapper mapper = new ObjectMapper();
UniversityList list = mapper.readValue(json, UniversityList.class));
University university = list.getUniversity().get(0)

Other option is to create custom deserializer for your University class

Here is demo:

public static void main(String[] args) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    SimpleModule module = new SimpleModule();
    module.addDeserializer(University.class, new UniversityDeserializer());
    mapper.registerModule(module);
    University university = mapper.readValue(json, University.class);
}

public static  class UniversityDeserializer extends JsonDeserializer<University> {
    private ObjectMapper unmodifiedMapper = new ObjectMapper();
    @Override
    public University deserialize(JsonParser p, DeserializationContext ctxt)
                                                                throws IOException{
        JsonNode node = p.readValueAsTree();
        JsonNode array = node.get("university");
        if (array != null && array.isArray()){
            JsonNode uniNode =  array.get(0);
            return unmodifiedMapper.treeToValue(uniNode, University.class);
        }
        return null;
    }
}

Upvotes: 2

Related Questions