Search code examples
javajsonparsingscalajson4s

Parsing a json object which has many fields


I want to parse json from a server and place it into a class. I use json4s for this. The issue is that a json object contains too many fields, it's about 40-50 of them, some of them have the long names.

I wonder, what will be a sensible way to store all of them, will I have to create 40-50 fields in a class? Remember, some of them will have the long names, as I said earlier.

I use Scala, but a Java's approach might be similar to it, so I added a tag of Java also.


Solution

  • I don't know json4s but in Jersey with Jackson, for example, you can use a Map to hold the Json data or you can use a POJO with all those names.

    Sometimes its better to have the names. It makes the code much easier to understand.

    Sometimes its better to use a Map. For example, if the field names change from time to time.

    If I recall it correctly, using pure Jackson you do something like this:

    String jsonString = ....; // This is the string of JSON stuff
    JsonFactory factory = new JsonFactory(); 
    ObjectMapper mapper = new ObjectMapper(factory);  // A Jackson class
    Map<String,Object> data = mapper.readValue(jsonString, HashMap.class); 
    

    You can use a TypeReference to make it a little cleaner as regards the generics. Jackson docs tell more about it. There is also more here: StackOverflow: JSON to Map