Image of Convert JSON to Java Object

ADVERTISEMENT

Introduction

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:

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:

  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:

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:

  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:
@JsonIgnoreProperties(ignoreUnknown = true)
  1. 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. To convert a JSON array to a List of objects use:
List<Student> students = mapper.readValue(jsonStr, new TypeReference<List<Student>>(){});
  1. To convert a JSON String to a HashMap use:
Map<String, Object> studentsMap = mapper.readValue(jsonStr, new TypeReference<Map<String,Object>>(){});

Summary

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

Next Steps

If you're interested in learning more about the basics of Java, coding, and software development, check out our Coding Essentials Guidebook for Developers, where we cover the essential languages, concepts, and tools that you'll need to become a professional developer.

Thanks and happy coding! We hope you enjoyed this article. If you have any questions or comments, feel free to reach out to jacob@initialcommit.io.