Java deserialize json to object with json

How to Convert JSON Object to Java Object with Jackson

In this tutorial, we’ll be taking a look at how to convert a JSON object into a Java Object using Jackson, an extremely popular data-binding library for Java.

Specifically, we’ll be working with this JSON object:

< "name":"David", "position":"Software Engineer", "skilltree":[ "Java", "Python", "JavaScript" ], "address":< "street":"Street", "streetNo":"123" > > 

Since we’re working with an external library, let’s add the dependency. If you’re using Maven, you can add it with:

dependency> groupId>com.fasterxml.jackson.core groupId> artifactId>jackson-databind artifactId> version>2.11.3 version> dependency> 

Or if you’re using Gradle, you can add:

implementation group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.11.3' 

Creating a Custom Class

With that done, we can create a simple custom class to host our Employee information from the JSON contents:

public class Employee < private String name; private POSITION position; private List skilltree; private Address address; // Constructors, Getters, Setters, toString() > 

Note: If we want Jackson to be able to automatically bind properties of our class and the properties in the JSON object, they have to have the exact same names. We’ll cover how to change this behavior a bit later. Also, you’ll want to have an empty constructor for instantiation.

Here, we’re using an enum, POSITION , which looks like this:

public class Address < private String street; private String streetNo; // Constructors, Getters and Setters, toString() > 

Convert JSON Object to Java Object

Jackson’s central class is the ObjectMapper . It’s the main API for object-related data-binding and you’ll use it all the time with Jackson.

To convert a JSON object into a Java object, you’ll use the readValue() method of the ObjectMapper instance, which deserializes it into the provided class reference:

String json = " < \"name\":\"David\", \"position\":\"SOFTWARE_ENGINEER\", \"skilltree\":[ \"Java\", \"Python\", \"JavaScript\" ], \"address\":< \"street\":\"Street\", \"streetNo\":\"123\" >>"; // ObjectMapper instantiation ObjectMapper objectMapper = new ObjectMapper(); // Deserialization into the `Employee` class Employee employee = objectMapper.readValue(json, Employee.class); // Print information System.out.println(employee); 

Running this code will result in:

Читайте также:  Html font size and color css

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Another way to create a let Jackson know into which class it should deserialize into is to use a TypeReference :

Employee employee = objectMapper.readValue(json, new TypeReference()<>); 

Printing this employee instance will also result in:

Both of these construct the given object and call the exact same deserialization process. So the only difference between these two calls is whether you’re making a static or dynamic reference to the type.

Источник

Gson – Parse JSON Array to Java Array or List

Learn to use Google GSON library to deserialize or parse a JSON array to a Java array or List object. It’s worth mentioning that JSON has only array datatype. Java has both – arrays and lists.

1. Parsing JSON Array as Root

To parse JSON, with array as root, we can use the following method syntax. Here ArrayItem is the class type of data elements in the array.

ArrayItem[] userArray = new Gson().fromJson(jsonSource, ArrayItem[].class); 

For converting such JSON array to a List, we need to use TypeToken class.

Type listType = new TypeToken>()<>.getType(); ArrayList list = gson.fromJson(jsonSource, listType); 

For demo purposes, we are using User.java as the JSON element type.

1.1. Converting JSON Array to Array of Objects

Java program to deserialize JSON array as root – to Java array of objects.

String userJson = "[, " + ", " + "]"; Gson gson = new Gson(); User[] userArray = gson.fromJson(userJson, User[].class); for(User user : userArray)
User [id=1, name=Alex] User [id=2, name=Brian] User [id=3, name=Charles]

1.2. Converting JSON Array to List of Objects

Читайте также:  Изображения

Java program to deserialize JSON array as root – to Java list of objects.

String userJson = "[, " + ", " + "]"; Gson gson = new Gson(); Type userListType = new TypeToken>()<>.getType(); ArrayList userArray = gson.fromJson(userJson, userListType); for(User user : userArray)
User [id=1, name=Alex] User [id=2, name=Brian] User [id=3, name=Charles]

2. Parsing JSON Array as Member

Gson parses JSON arrays as members without difficulty if they are non-root objects. We can use the fromJson() method in the usual manner and it will parse the JSON array correctly to the required java array or list.

2.1. Member JSON Array to Java Array

Java program to deserialize JSON array as member object – to Java array of objects as member field.

String departmentJson = ", " + ", " + "]>"; Gson gson = new Gson(); Department department = gson.fromJson(departmentJson, Department.class); System.out.println(department);
Department [id=1, name=HR, users=[User [id=1, name=Alex], User [id=2, name=Brian], User [id=3, name=Charles]]]

2.2. Member JSON Array to Java List

Java program to deserialize JSON array as member object – to Java list of objects a member field.

public class Department < private long id; private String name; private Listusers; //Getters and Setters >
String departmentJson = ", " + ", " + "]>"; Gson gson = new Gson(); Department department = gson.fromJson(departmentJson, Department.class); System.out.println(department);
Department [id=1, name=HR, users=[User [id=1, name=Alex], User [id=2, name=Brian], User [id=3, name=Charles]]]

Drop me your question related to gson parse JSON array to java lists and arrays.

Источник

Оцените статью