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:
1 2 3 4 5 6 | public static Student convertUsingGson(String jsonStr) { Gson gson = new Gson(); Student student = gson.fromJson(jsonStr, Student.class); return student; } |
Some points to be considered when using Gson:
- If the JSON string holds an invalid object attribute, then Gson implicitly ignores it.
- 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | public static Student convertUsingJackson(String jsonStr) { Student student = null; try { ObjectMapper mapper = new ObjectMapper(); student = mapper.readValue(jsonStr, Student.class); } catch(Exception ex) { System.out.println("Error while converting JSON string to Student object."); ex.printStackTrace(); } return student; } |
Some points to be considered when using Jackson:
- If the POJO doesn’t contain a default constructor, then the conversion fails.
- If the JSON string holds any invalid object attribute, then the conversion fails unless you add explicitly at the POJO level this annotation:1@JsonIgnoreProperties(ignoreUnknown = true)
- If the JSON string misses some object attributes, then only the attributes included in the JSON are converted, other attributes take their default values.
- To convert a JSON array to a List of objects use:1List<Student> students = mapper.readValue(jsonStr, new TypeReference<List<Student>>(){});
- To convert a JSON String to a HashMap use:1Map<String, Object> studentsMap = mapper.readValue(jsonStr, new TypeReference<Map<String,Object>>(){});