Parse and objectize JSON using the @JsonProperty annotation of the Java library Jackson

Overview

--Use Jackson, Java's JSON library --Try parsing a JSON string and making it an object in several ways -Objectize using @ JsonProperty annotation --Try writing without annotations for comparison

JSON to be parsed this time

{
  "user": {
    "name": "Pompom Pudding",
    "score": {
      "kokugo": "good",
      "sansuu": 100
    },
    "favorites": ["soccer", "puzzle"]
  }
}

Parse and objectize JSON in several ways

When directly creating a Map object without preparing a class (no annotation used)

You can get a Map object by passing Map.class as the second argument of ObjectMapper # readValue. Creating an object is simple, but retrieving the desired data from the created object is complicated.

ObjectMapper mapper = new ObjectMapper();
Map obj = mapper.readValue(json, Map.class);
System.out.println(obj);
String name = (String)(((Map)obj.get("user")).get("name"));
System.out.println("name=" + name);

Output example.

{user={name=Pompom Pudding, score={kokugo=good, sansuu=100}, favorites=[soccer, puzzle]}}
name=Pompom Pudding

When preparing a public instance variable in the class (no annotation used)

It can be made into an object by preparing a public instance variable or getter setter. In that case, it is not necessary to write @ JsonProperty annotation.

import java.util.Map;
public class PublicUserObject {
  public Map user;
}
ObjectMapper mapper = new ObjectMapper();
PublicUserObject obj = mapper.readValue(json, PublicUserObject.class);
System.out.println(obj);
String name = (String)obj.user.get("name");
System.out.println("name=" + name);

Output example.

PublicUserObject@e6abefac
name=Pompom Pudding

When preparing a private instance variable in the class (using annotation)

When using a private instance variable, it is necessary to specify the JSON key (name) you want to map with @ JsonProperty.

import java.util.Map;
import com.fasterxml.jackson.annotation.JsonProperty;

public class SimpleUserObject {

  @JsonProperty("user")
  private Map user;

  public Map getUser() {
    return user;
  }

  @Override
  public String toString() {
    return getClass().getName() + ": user:" + user;
  }
}
ObjectMapper mapper = new ObjectMapper();
SimpleUserObject obj = mapper.readValue(json, SimpleUserObject.class);
System.out.println(obj);
String name = (String) obj.getUser().get("name");
System.out.println("name=" + name);

Output example.

SimpleUserObject: user:{name=Pompom Pudding, score={kokugo=good, sansuu=100}, favorites=[soccer, puzzle]}
name=Pompom Pudding

When a private instance variable and access method are prepared in the class (using annotation)

If you create an accessor method a little more firmly, it will be easier to use from an external class.

import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonProperty;

public class AccessorUserObject {

  @JsonProperty("user")
  private Map user;

  public String getName() {
    return (String) user.get("name");
  }

  private Map getScore() {
    return (Map) user.get("score");
  }

  public String getKokugoScore() {
    return (String) getScore().get("kokugo");
  }

  public int getSansuuScore() {
    return (int) getScore().get("sansuu");
  }

  public List getFavorites() {
    return (List) user.get("favorites");
  }

  @Override
  public String toString() {
    return getClass().getName() +
        ", getName: " + getName() +
        ", getKokugoScore: " + getKokugoScore() +
        ", getSansuuScore: " + getSansuuScore() +
        ", getFavorites: " + getFavorites();
  }
}
ObjectMapper mapper = new ObjectMapper();
AccessorUserObject obj = mapper.readValue(json, AccessorUserObject.class);
System.out.println(obj);
String name = obj.getName();
System.out.println("name=" + name);

Output example.

AccessorUserObject, getName: Pompom Pudding, getKokugoScore: good, getSansuuScore: 100, getFavorites: [soccer, puzzle]
name=Pompom Pudding

When a class for mapping is prepared (using annotation)

Prepare a class and an inner class for mapping JSON data.

import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;

public class StructedUserObject {

  @JsonProperty("user")
  public User user;

  public static class User {

    public String name;
    public Score score;
    public List favorites;

    @Override
    public String toString() {
      return getClass().getSimpleName()
          + ": name: " + name
          + ", score: " + score
          + ", favorites: " + favorites;
    }
  }

  public static class Score {

    public String kokugo;
    public int sansuu;

    @Override
    public String toString() {
      return getClass().getSimpleName()
          + ": kokugo: " + kokugo
          + ", sansuu: " + sansuu;
    }
  }

  @Override
  public String toString() {
    return getClass().getName() + ": user:" + user;
  }
}
ObjectMapper mapper = new ObjectMapper();
StructedUserObject obj = mapper.readValue(json, StructedUserObject.class);
System.out.println(obj);
String name = obj.user.name;
System.out.println("name=" + name);

Output example.

StructedUserObject: user:User: name: Pompom Pudding, score: Score: kokugo: good, sansuu: 100, favorites: [soccer, puzzle]
name=Pompom Pudding

The file and execution environment used for this operation check

Java and Maven

$ mvn --version
Apache Maven 3.6.1 (d66c9c0b3152b2e69ee9bac180bb8fcc8e6af555; 2019-04-05T04:00:29+09:00)
Maven home: /usr/local/Cellar/maven/3.6.1/libexec
Java version: 11.0.2, vendor: Oracle Corporation, runtime: /Library/Java/JavaVirtualMachines/openjdk-11.0.2.jdk/Contents/Home
Default locale: ja_JP, platform encoding: UTF-8
OS name: "mac os x", version: "10.14.5", arch: "x86_64", family: "mac"

File list

├── pom.xml
├── src
│   └── main
│       └── java
│           └── info
│               └── maigo
│                   └── lab
│                       └── myjacksonsamples
│                           ├── AccessorUserObject.java
│                           ├── Main.java
│                           ├── PublicUserObject.java
│                           ├── SimpleUserObject.java
│                           └── StructedUserObject.java
└── user.json

pom.xml

Prepare a pom.xml file so that it can be built and executed by Maven. Add Jackson libraries jackson-core, jackson-databind, jackson-annotations to dependencies. Add exec-maven-plugin to plugins so that you can run Java programs from Maven.

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>info.maigo.lab</groupId>
  <artifactId>my-jackson-samples</artifactId>
  <version>1.0-SNAPSHOT</version>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>11</maven.compiler.source>
    <maven.compiler.target>11</maven.compiler.target>
  </properties>

  <!-- $ mvn exec:java -->
  <!-- https://www.mojohaus.org/exec-maven-plugin/ -->
  <build>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
        <version>1.6.0</version>
        <configuration>
          <mainClass>info.maigo.lab.myjacksonsamples.Main</mainClass>
        </configuration>
      </plugin>
    </plugins>
  </build>

  <dependencies>

    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.9.9</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.9</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.9.9</version>
    </dependency>

  </dependencies>

</project>

A command to generate a JAR file.

$ mvn package

A command to execute a sample program.

$ mvn exec:java

Java source code

Main.java

package info.maigo.lab.myjacksonsamples;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;

import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {

    public static void main(String[] args) throws IOException {
        String json = Files.readString(Path.of("user.json"), StandardCharsets.UTF_8);
        createMappedUserObject(json);
        createPublicUserObject(json);
        createSimpleUserObject(json);
        createAccessorUserObject(json);
        createStructedUserObject(json);
    }

    private static void createMappedUserObject(String json) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        Map obj = mapper.readValue(json, Map.class);
        System.out.println(obj);
        String name = (String) (((Map) obj.get("user")).get("name"));
        System.out.println("name=" + name);
    }

    private static void createPublicUserObject(String json) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        PublicUserObject obj = mapper.readValue(json, PublicUserObject.class);
        System.out.println(obj);
        String name = (String) obj.user.get("name");
        System.out.println("name=" + name);
    }

    private static void createSimpleUserObject(String json) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        SimpleUserObject obj = mapper.readValue(json, SimpleUserObject.class);
        System.out.println(obj);
        String name = (String) obj.getUser().get("name");
        System.out.println("name=" + name);
    }

    private static void createAccessorUserObject(String json) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        AccessorUserObject obj = mapper.readValue(json, AccessorUserObject.class);
        System.out.println(obj);
        String name = obj.getName();
        System.out.println("name=" + name);
    }

    private static void createStructedUserObject(String json) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        StructedUserObject obj = mapper.readValue(json, StructedUserObject.class);
        System.out.println(obj);
        String name = obj.user.name;
        System.out.println("name=" + name);
    }
}

PublicUserObject.java

package info.maigo.lab.myjacksonsamples;

import java.util.Map;

public class PublicUserObject {

    public Map user;

}

SimpleUserObject.java

package info.maigo.lab.myjacksonsamples;

import com.fasterxml.jackson.annotation.JsonProperty;

import java.util.Map;

public class SimpleUserObject {

    @JsonProperty("user")
    private Map user;


    public Map getUser() {
        return user;
    }

    @Override
    public String toString() {
        return getClass().getName() + ": user:" + user;
    }
}

AccessorUserObject.java

package info.maigo.lab.myjacksonsamples;

import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonProperty;

public class AccessorUserObject {

    @JsonProperty("user")
    private Map user;

    public String getName() {
        return (String) user.get("name");
    }

    private Map getScore() {
        return (Map) user.get("score");
    }

    public String getKokugoScore() {
        return (String) getScore().get("kokugo");
    }

    public int getSansuuScore() {
        return (int) getScore().get("sansuu");
    }

    public List getFavorites() {
        return (List) user.get("favorites");
    }

    @Override
    public String toString() {
        return getClass().getName() +
                ", getName: " + getName() +
                ", getKokugoScore: " + getKokugoScore() +
                ", getSansuuScore: " + getSansuuScore() +
                ", getFavorites: " + getFavorites();
    }
}

StructedUserObject.java

package info.maigo.lab.myjacksonsamples;

import java.util.List;

import com.fasterxml.jackson.annotation.JsonProperty;

public class StructedUserObject {

    @JsonProperty("user")
    public User user;

    public static class User {

        public String name;
        public Score score;
        public List favorites;

        @Override
        public String toString() {
            return getClass().getSimpleName()
                    + ": name: " + name
                    + ", score: " + score
                    + ", favorites: " + favorites;
        }
    }

    public static class Score {

        public String kokugo;
        public int sansuu;

        @Override
        public String toString() {
            return getClass().getSimpleName()
                    + ": kokugo: " + kokugo
                    + ", sansuu: " + sansuu;
        }
    }

    @Override
    public String toString() {
        return getClass().getName() + ": user:" + user;
    }
}

user.json

{
  "user": {
    "name": "Pompom Pudding",
    "score": {
      "kokugo": "good",
      "sansuu": 100
    },
    "favorites": ["soccer", "puzzle"]
  }
}

Reference material

Recommended Posts

Parse and objectize JSON using the @JsonProperty annotation of the Java library Jackson
[Java] Try editing the elements of the Json string using the library
Convert JSON and YAML in Java (using Jackson and SnakeYAML)
JSON in Java and Jackson Part 1 Return JSON from the server
Display Japanese calendar and days of the week using java8 standard class
[Java] Output the result of ffprobe -show_streams in JSON and map it to an object with Jackson
I compared the characteristics of Java and .NET
JSON with Java and Jackson Part 2 XSS measures
Convert Java enum enums and JSON to and from Jackson
Please note the division (division) of java kotlin Int and Int
The comparison of enums is ==, and equals is good [Java]
[Java] Sort the list using streams and lambda expressions
Try implementing the Eratosthenes sieve using the Java standard library
Organizing the current state of Java and considering the future
Java language from the perspective of Kotlin and C #
I summarized the types and basics of Java exceptions
Try global hooking in Java using the JNativeHook library
[Java] Convert JSON to Java and Java to JSON-How to use GSON and Jackson-
Mutual conversion between Java objects and JSON using Moshi
[Java10] Be careful of using var and generics together
History of Java annotation
Send and receive simple messages using the Kafka component of the Apache Camel framework (Java DSL)
[Note] Java Output of the sum of odd and even elements
I didn't understand the behavior of Java Scanner and .nextLine ().
I tried to summarize the basics of kotlin and java
[Java] Comparison method of character strings and comparison method using regular expressions
Command to check the number and status of Java threads
Check the status of Java application without using monitoring tool
Java beginners briefly summarized the behavior of Array and ArrayList
[Ruby] Creating code using the concept of classes and instances
[Java] [jackson] Corresponds to the trailing comma (trailing comma) when parsing JSON.
The story of pushing Java to Heroku using the BitBucket pipeline
I tried using the CameraX library with Android Java Fragment
[Java] I thought about the merits and uses of "interface"
Challenges and alternative research of Java serial communication library RXTX
[Java] JSON communication with jackson
[Java] Creation of original annotation
Advantages and disadvantages of Java
[Java] Various summaries attached to the heads of classes and members
[Java] Get the dates of the past Monday and Sunday in order
Java, JS (jQuery) and Ajax. Get a specific value of JSON.
Read the first 4 bytes of the Java class file and output CAFEBABE
From fledgling Java (3 years) to Node.js (4 years). And the impression of returning to Java
I tried to summarize the methods of Java String and StringBuilder
[Android] Convert Map to JSON using GSON in Kotlin and Java
Is the version of Elasticsearch you are using compatible with Java 11?