Convert JSON to Java Object

This tutorials shows 2 ways for converting a JSON string to a Java object.

1- Gson

Gson is the most popular library for converting JSON string to Java objects.

With Gson, you can do the conversion in one line as the following:

Some points to be considered when using Gson:

  1. If the JSON string holds an invalid object attribute, then Gson implicitly ignores it.
  2. If the JSON string misses some object attributes, then only the attributes included in the JSON are converted, other attributes take their default values.

2- Jackson

Another common library used for converting JSON String to Java object is Jackson.

With Jackson, you do the conversion as the following:

Some points to be considered when using Jackson:

  1. If the POJO doesn’t contain a default constructor, then the conversion fails.
  2. If the JSON string holds any invalid object attribute, then the conversion fails unless you add explicitly at the POJO level this annotation:
  3. If the JSON string misses some object attributes, then only the attributes included in the JSON are converted, other attributes take their default values.
  4. To convert a JSON array to a List of objects use:
  5. To convert a JSON String to a HashMap use:

     

husseinterek

Founder of programmergate.com, I have a passion in software engineering and everything related to java environment.

You may also like...

Leave a Reply

avatar