[Java] Convert JSON to Java and Java to JSON-How to use GSON and Jackson-

Overview

I will summarize the JSON → Java and Java → JSON methods that are often used when using the Web API in Java. Also, how to HTTP POST and HTTP GET JSON will be summarized in the next article.

- [This article] I will summarize how to handle JSON in Java </ b> --There are two ways to convert JSON to Java (serialize) and Java to JSON (serialize). --How to use GSON for the library --How to use Jackson for the library

-[Next article] I will also summarize how to POST and GET JSON by HTTP communication in Java --I will explain two ways to perform HTTP communication with Java. --How to use OkHttp3 --How to use the standard Java package ** HttpUrlConnection **

Shortest course-Thinking with JSON-

Consider the shortest course when the JSON string you want to parse already exists, such as when hitting an external API. Since the model class ** auto-generated site ** is used, it is OK if there is a JSON string (JSON schema is better).

Sample JSON string: example.json


{
    "person": {
        "firstName": "John",
        "lastName": "Doe",
        "address": "NewYork",
        "pets": [
            {"type": "Dog", "name": "Jolly"},
            {"type": "Cat", "name": "Grizabella"},
            {"type": "Fish", "name": "Nimo"}
        ]
    }
}

GSON and Jackson

When it comes to JSON operations in Java, I often use two libraries, ** GSON ** and ** Jackson **. I can't say which one is better, so I will explain both.

GSON [Library] made by Google (https://github.com/google/gson) image.png

Jackson Performance-focused library image.png

GSON edition

Map JSON to Java using ** GSON **

Let's start with GSON. If you have JSON, that is, if you want to create a Java parser from raw JSON strings, it is easy to use jsonschema2pojo, so I will try it.

Click here for the source code of this chapter https://github.com/riversun/java-json-gson-jackson-http/tree/master/src/main/java/com/example/gson

GSON library dependencies

The method of specifying the GSON library is as follows

■ GSON latest library (maven repository) https://mvnrepository.com/artifact/com.google.code.gson/gson

■ GSON ** maven ** setting example

pom.xml


<dependency>
	<groupId>com.google.code.gson</groupId>
	<artifactId>gson</artifactId>
	<version>2.8.5</version>
</dependency>

■ GSON ** gradle ** setting example

build.gradle


compile 'com.google.code.gson:gson:2.8.5'

(1) Automatically generate model class (POJO) using jsonschema2pojo

Go to the following site and paste the JSON above http://www.jsonschema2pojo.org/

  • If you are uncomfortable with an external site, you can do it yourself using Library.

image.png

■ Set as follows on the site and press ** Zip ** to automatically generate the model class

Package: ** com.example.gson ** (Package name, whatever, but the source is automatically generated with that package name) ClassN name: ** Model ** (Pojo's top class name) Target language:Java Source type: ** JSON ** (estimate the model class from the JSON string itself) Annotation style: ** Gson ** (use GSON for parser) ☑ ** Allow additional properties ** (JSON can be mixed with unknowns)

A ** Zip ** file is generated, so when you download and open it, three java files are automatically generated as shown below.

(2) ** Check the automatically generated ** model class (POJO)

■ ** Model.java ** ・ ・ ・ Highest class

Model.java


package com.example.gson;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Model {
    @SerializedName("person")
    @Expose
    public Person person;
}

■ ** Person.java ** ・ ・ ・ ** "pets": [] ** that is specified as an array becomes ** List **

Person.java


package com.example.gson;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Person {
    @SerializedName("firstName")
    @Expose
    public String firstName;
    @SerializedName("lastName")
    @Expose
    public String lastName;
    @SerializedName("address")
    @Expose
    public String address;
    @SerializedName("pets")
    @Expose
    public List<Pet> pets = null;
}

Pet.java

Pet.java


package com.example.gson;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Pet {
    @SerializedName("type")
    @Expose
    public String type;
    @SerializedName("name")
    @Expose
    public String name;
}

(3) Convert ** JSON to Java ** using GSON

Convert JSON to Java, that is, use GSON to load a JSON string into a Java model class The key code is as follows

Gson gson = new Gson();
Model model = gson.fromJson(json, Model.class);

The whole code looks like this

GsonJson2Java.java

GsonJson2.java


package com.example.gson;

import com.google.gson.Gson;

public class GsonJson2Java {
    public static void main(String[] args) {
        String json = 
                "{" +
                "    \"person\": {" +
                "        \"firstName\": \"John\"," +
                "        \"lastName\": \"Doe\"," +
                "        \"address\": \"NewYork\"," +
                "        \"pets\": [" +
                "            {\"type\": \"Dog\", \"name\": \"Jolly\"}," +
                "            {\"type\": \"Cat\", \"name\": \"Grizabella\"}," +
                "            {\"type\": \"Fish\", \"name\": \"Nimo\"}" +
                "        ]" +
                "    }" +
                "}";

        Gson gson = new Gson();
        Model model = gson.fromJson(json, Model.class);

        System.out.println("firstName:" + model.person.firstName);
        System.out.println("lastName:" + model.person.lastName);
        System.out.println("address:" + model.person.address);
        System.out.println("1st pet:" + model.person.pets.get(0).name);
    }
}

Execution result


firstName:John
lastName:Doe
address:NewYork
1st pet:Jolly

(4) Convert ** Java → JSON ** using GSON

Now, let's do JSON from Java. JSONize Java model class (POJO).

Gson gson = new Gson();
String json = gson.toJson(model);

GsonJava2Json.java

GsonJava2Json.java


package com.example.gson;

import java.util.ArrayList;
import com.google.gson.Gson;

public class GsonJava2Json {
    public static void main(String[] args) {

        Model model = new Model();
        model.person = new Person();
        model.person.firstName = "John";
        model.person.lastName = "Do";
        model.person.address = "New York";

        model.person.pets = new ArrayList<Pet>();

        Pet pet1 = new Pet();
        pet1.type = "dog";
        pet1.name = "Jolly";
        model.person.pets.add(pet1);

        Pet pet2 = new Pet();
        pet2.type = "Cat";
        pet2.name = "Grizabella";
        model.person.pets.add(pet2);

        Pet pet3 = new Pet();
        pet3.type = "fish";
        pet3.name = "Nemo";
        model.person.pets.add(pet3);

        Gson gson = new Gson();
        String json = gson.toJson(model);

        System.out.println(json);
    }
}

When this was executed, JSON could be output from the model class as follows.

Execution result


{"person":{"firstName":"John","lastName":"Do","address":"New York","pets":[{"type":"dog","name":"Jolly"},{"type":"Cat","name":"Grizabella"},{"type":"fish","name":"Nemo"}]}}

(5) Use GSON to format and output JSON (Pretty Printing)

If you do this, the JSON will be indented and nicely formatted and will come out.

Gson gson2 = new GsonBuilder().setPrettyPrinting().create();
String prettyJson = gson2.toJson(model);
System.out.println(prettyJson);

Execution result

{
  "person": {
    "firstName": "John",
    "lastName": "Do",
    "address": "New York",
    "pets": [
      {
        "type": "dog",
        "name": "Jolly"
      },
      {
        "type": "Cat",
        "name": "Grizabella"
      },
      {
        "type": "fish",
        "name": "Nemo"
      }
    ]
  }
}

Jackson edition

Jackson has 1.x series and 2.x series, but uses 2.x series

Map JSON to Java using ** Jackson **

Click here for the source code of this chapter https://github.com/riversun/java-json-gson-jackson-http/tree/master/src/main/java/com/example/jackson

Jackson library dependencies

The method of specifying the library of Jackson is as follows

■ Jackson's latest library (maven repository) https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind

■ Jackson's ** maven ** setting example

pom.xml


<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-databind</artifactId>
	<version>2.9.8</version>
</dependency>

■ Jackson's ** gradle ** setting example

build.gradle


compile 'com.fasterxml.jackson.core:jackson-databind:2.9.8'

(1) Automatically generate model class (POJO) using jsonschema2pojo

Go to the following site and paste the JSON above http://www.jsonschema2pojo.org/

image.png

■ Set as follows on the site and press ** Zip ** to automatically generate the model class

Package: ** com.example. jackson </ font> ** (Package name, whatever, but the source is automatically generated with that package name) ClassN name: ** Model ** (Pojo's top class name) Target language:Java Source type: ** JSON ** (estimate the model class from the JSON string itself) Annotation style: ** jackson 2.x ** </ font> (use Jackson 2.x as parser) ☑ ** Allow additional properties ** (JSON can be mixed with unknowns)

A ** Zip ** file is generated, so when you download and open it, three java files are automatically generated as shown below.

(2) ** Check the automatically generated ** model class (POJO)

■ ** Model .java ** ・ ・ ・ The highest class. It is characteristic that ** @JsonAnyGetter ** is set to accept additional properties. It also makes it more verbose than GSON.

Model.java


package com.example.jackson;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
    "person"
})
public class Model {
    @JsonProperty("person")
    public Person person;
    @JsonIgnore
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();
    @JsonAnyGetter
    public Map<String, Object> getAdditionalProperties() {
        return this.additionalProperties;
    }
    @JsonAnySetter
    public void setAdditionalProperty(String name, Object value) {
        this.additionalProperties.put(name, value);
    }
}

■ ** Person.java ** ・ ・ ・ ** @JsonPropertyOrder ** can be used to constrain the order of appearance. An array specified like ** "pets": [] ** becomes ** List **.

Person.java


package com.example.jackson;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
    "firstName",
    "lastName",
    "address",
    "pets"
})
public class Person {
    @JsonProperty("firstName")
    public String firstName;
    @JsonProperty("lastName")
    public String lastName;
    @JsonProperty("address")
    public String address;
    @JsonProperty("pets")
    public List<Pet> pets = null;
    @JsonIgnore
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();
    @JsonAnyGetter
    public Map<String, Object> getAdditionalProperties() {
        return this.additionalProperties;
    }
    @JsonAnySetter
    public void setAdditionalProperty(String name, Object value) {
        this.additionalProperties.put(name, value);
    }
}

Pet.java

Pet.java


package com.example.jackson;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
    "type",
    "name"
})
public class Pet {
    @JsonProperty("type")
    public String type;
    @JsonProperty("name")
    public String name;
    @JsonIgnore
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();
    @JsonAnyGetter
    public Map<String, Object> getAdditionalProperties() {
        return this.additionalProperties;
    }
    @JsonAnySetter
    public void setAdditionalProperty(String name, Object value) {
        this.additionalProperties.put(name, value);
    }
}

(3) Use Jackson to convert ** JSON to Java **

Convert JSON to Java, that is, use Jackson to load a JSON string into a Java model class The key code is as follows

ObjectMapper mapper = new ObjectMapper();
Model model = mapper.readValue(json, Model.class);

The whole code looks like this

JacksonJson2Java.java

JacksonJson2Java.java


package com.example.jackson;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonJson2Java {
    public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
        String json = "{" +
                "    \"person\": {" +
                "        \"firstName\": \"John\"," +
                "        \"lastName\": \"Doe\"," +
                "        \"address\": \"NewYork\"," +
                "        \"pets\": [" +
                "            {\"type\": \"Dog\", \"name\": \"Jolly\"}," +
                "            {\"type\": \"Cat\", \"name\": \"Grizabella\"}," +
                "            {\"type\": \"Fish\", \"name\": \"Nimo\"}" +
                "        ]" +
                "    }" +
                "}";

        ObjectMapper mapper = new ObjectMapper();
        Model model = mapper.readValue(json, Model.class);

        System.out.println("firstName:" + model.person.firstName);
        System.out.println("lastName:" + model.person.lastName);
        System.out.println("address:" + model.person.address);
        System.out.println("1st pet:" + model.person.pets.get(0).name);
    }
}

(4) Use Jackson to convert ** Java to JSON **

Now, let's do JSON from Java. JSONize Java model class (POJO).

ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(model);

JacksonJava2Json.java

JacksonJava2Json.java


package com.example.jackson;
import java.util.ArrayList;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonJava2Json {
    public static void main(String[] args) throws JsonProcessingException {

        Model model = new Model();
        model.person = new Person();
        model.person.firstName = "John";
        model.person.lastName = "Do";
        model.person.address = "New York";
        model.person.pets = new ArrayList<Pet>();
        Pet pet1 = new Pet();
        pet1.type = "dog";
        pet1.name = "Jolly";
        model.person.pets.add(pet1);
        Pet pet2 = new Pet();
        pet2.type = "Cat";
        pet2.name = "Grizabella";
        model.person.pets.add(pet2);
        Pet pet3 = new Pet();
        pet3.type = "fish";
        pet3.name = "Nemo";
        model.person.pets.add(pet3);

        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(model);
        System.out.println(json);
    }
}

When this was executed, JSON could be output from the model class as follows.

Execution result


{"person":{"firstName":"John","lastName":"Do","address":"New York","pets":[{"type":"dog","name":"Jolly"},{"type":"Cat","name":"Grizabella"},{"type":"fish","name":"Nemo"}]}}

(5) Using Jackson, format JSON (Pretty Printing) and output

If you do this, the JSON will be indented and nicely formatted and will come out.

ObjectMapper mapper2 = new ObjectMapper();
String prettyJson = mapper2.writerWithDefaultPrettyPrinter().writeValueAsString(model);
System.out.println(prettyJson);

Execution result

{
  "person" : {
    "firstName" : "John",
    "lastName" : "Do",
    "address" : "New York",
    "pets" : [ {
      "type" : "dog",
      "name" : "Jolly"
    }, {
      "type" : "Cat",
      "name" : "Grizabella"
    }, {
      "type" : "fish",
      "name" : "Nemo"
    } ]
  }
}

Summary

--I explained how to easily execute JSON → Java and Java → JSON using GSON. --The source code using GSON is here

--I explained the same for Jackson. --The source code using Jackson is here --The method of POSTing and GET JSON via HTTP communication is summarized in here.

Recommended Posts