1

I need to parse the following JSON and add values from it into three different Java objects. I was thinking to form other 3 Jsons in order to do this. I have some issues with parsing, as the JSON is a little bit complicated. The JSON is below:

{
 "totalCount": 1,
 "results": [
   {
     "teleCommunications": [
       {
         "areaCode": "100",
         "telephoneNumber": "300-2444",
         "internationalAreaCode": "",
         "communicationType": 1
       },
       {
         "areaCode": "100",
         "telephoneNumber": "200-2555",
         "internationalAreaCode": "",
         "communicationType": 5
       }
     ],
     "delegate": {
       "id": 0,
       "range": 0,
     },
     "name": "Andrew",
     "composedKey": {
       "id": 615,
       "range": 50,
     },
     "isBranchAddress": false,
     "emailAddresses": [
       {
         "emailAddressType": 9,
         "emailAddress": "andrew.brown@gmail.com"
       }
     ],
     "name": "Brown",
     "zipCodeCity": "65760 Leipzig",
     "salutation": "Mr.",
     "openingDate": "2019-09-20",
     "streetHouseNumber": "Offenbach. 37",
     "modificationTimestamp": "2018-01-27"
   }
 ]
}

I need to get separately the values from name, zipCodeCity, salutation, openingDate, streetHouseNumber in a JSON ( or any other way) , emailAddresses in a different JSON and the other data in another one.

I tried with this piece of code:

ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
HashMap<String, Object> result  = new ObjectMapper().readValue(response, HashMap.class);

Object object = result.get("results");


List<HashMap<String, String>> jsonValues = (List<HashMap<String, String>>)object;

     for(String key : jsonValues.get(0).keySet()){

         System.out.println("name value " + jsonValues.get(0).get("name"));
         System.out.println("zip code City " + jsonValues.get(0).get("zipCodeCity"));

    }

The problem is that I would not go for such a hardcoded way...it is not very suitable. Does anyone know a better approach for storing the values I need and parsing the Json more optimally?

Thank you

pdem
  • 3,880
  • 1
  • 24
  • 38
Maria1995
  • 439
  • 1
  • 5
  • 21

3 Answers3

1

Look for this link, there's a demo application specially for you: https://github.com/nalmelune/jackson-demo-58591850 (look at JacksonTest)

First of all, you'll need data-classes for this (or so called dto), representing structure. You can use online generators for that (google "json to java dto online") or do it yourself. For example, here's root object (see github link for more):

public class Root {
   private int totalCount;
   private List<Results> results;

   public void setTotalCount(int totalCount) {
       this.totalCount = totalCount;
   }

   public int getTotalCount() {
       return this.totalCount;
   }

   public void setResults(List<Results> results) {
       this.results = results;
   }

   public List<Results> getResults() {
       return this.results;
   }
}

Then configure your ObjectMapper:

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

And use it (don't create new mapper, as it is in your example):

Root result = mapper.readValue(response, Root.class);

Finally, you can access it as usual Plain Old Java Objects:

    for (Results resultItem : result.getResults()) {
        System.out.println(resultItem.getSalutation());
        System.out.println(resultItem.getName());
        System.out.println(resultItem.getZipCodeCity());
        System.out.println(resultItem.getOpeningDate());
        System.out.println(resultItem.getStreetHouseNumber());
    }

To make it work be sure validate your json (there were invalid commas after "range", and "name" comes twice and so on, it fixed on github). And be sure to include jsr310 in classpath by adding com.fasterxml.jackson.datatype:jackson-datatype-jsr310 module. You will need it for LocalDate and LocalDateTime objects.

Nalmelune
  • 78
  • 2
  • 10
0

You may create java class something like below

@Data
 class MyCustomClass{
    int totalCount;
    List<TeleCommunicationDetail> results;
   // other props
 }

Next you can add attributes to TeleCommunicationDetail and finally you can use MyCustomClass reaonseInJavaObject = objectMapper.readValue(myJson,MyCustomClass.class);

Refer to this question for details.

Ravik
  • 694
  • 7
  • 12
0

Your approach is correct, as you simply read your JSON object as Map<String, Object> which always will work (as long as JSON Object is valid). And then you retrieve your values that you expect to be there. Another approach is to create a Class that maps to your original JSON and parse JSON with ObjectMapper into your class. Then you can retrieve your data with your class setters and getters. In this case, you don't need to use key Strings like "results" etc but you have to ensure that your JSON is not only valid JSON but always conforms to your class. Pick your option...

Michael Gantman
  • 7,315
  • 2
  • 19
  • 36