Sample code to serialize and deserialize Java Enum enums and JSON in Jackson

Overview

--Convert values in Java Enum enums and JSON --Use the abstract classes JsonSerializer and JsonDeserializer provided by Jackson

Operation check environment

Sample code

package com.example.humansex;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;

/**
 * ISO 5218 (Code for notation of human gender)An enumeration type that represents.
 *Gender code:unknown=0,male=1,Female=2,Not applicable=9
 */
public enum HumanSex {

  /**
   *unknown=0,male=1,Female=2,Not applicable=9
   */
  NOT_KNOWN(0), MALE(1), FEMALE(2), NOT_APPLICABLE(9);

  private final int code;

  private HumanSex(int code) {
    this.code = code;
  }

  /**
   *Returns the gender code.
   */
  public int getCode() {
    return code;
  }

  /**
   *Returns a HumanSex enumeration constant that matches the gender code.
   *
   * @param code Gender code
   * @return HumanSex enumeration constant
   */
  public static HumanSex codeOf(int code) {
    for (HumanSex value : HumanSex.values()) {
      if (code == value.getCode()) {
        return value;
      }
    }
    return null; //Does not match
  }

  /**
   *A class that serializes a HumanSex object to JSON.
   */
  public static class Serializer extends JsonSerializer<HumanSex> {

    /**
     *Gender code the HumanSex object when generating JSON(Integer value)Convert to.
     */
    @Override
    public void serialize(HumanSex value, JsonGenerator generator, SerializerProvider serializers) throws IOException {
      generator.writeNumber(value.getCode());
    }
  }

  /**
   *A class that deserializes a HumanSex object from JSON.
   */
  public static class Deserializer extends JsonDeserializer<HumanSex> {

    /**
     *Gender code when parsing JSON(Integer value)To a HumanSex object.
     */
    @Override
    public HumanSex deserialize(JsonParser parser, DeserializationContext context) throws IOException {
      return HumanSex.codeOf(parser.getIntValue());
    }
  }
}
package com.example;

import com.example.humansex.HumanSex;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

import java.util.ArrayList;
import java.util.List;

public class MyData {

  public List<Person> personList = new ArrayList<>();

  @Override
  public String toString() {
    StringBuilder buf = new StringBuilder();
    for (Person person : personList) {
      buf.append(person + System.lineSeparator());
    }
    return buf.toString();
  }

  public static class Person {

    public String name;

    //Specify the class to be used when JSON generation / analysis by Jackson with annotation
    @JsonSerialize(using = HumanSex.Serializer.class)
    @JsonDeserialize(using = HumanSex.Deserializer.class)
    public HumanSex sex;

    public Person() {
    }

    public Person(String name, HumanSex sex) {
      this.name = name;
      this.sex = sex;
    }

    @Override
    public String toString() {
      return "name=[" + name + "], sex=[" + sex.toString() + "]";
    }
  }
}
package com.example;

import com.example.humansex.HumanSex;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.io.StringWriter;

public class App {

  public static void main(String[] args) throws IOException {

    //Generate data object
    MyData inputData = new MyData();
    inputData.personList.add(new MyData.Person("Peko",   HumanSex.NOT_KNOWN));
    inputData.personList.add(new MyData.Person("Anubis", HumanSex.MALE));
    inputData.personList.add(new MyData.Person("Isis",   HumanSex.FEMALE));
    inputData.personList.add(new MyData.Person("Robot",  HumanSex.NOT_APPLICABLE));

    //Generate JSON string from data object in Jackson
    StringWriter out = new StringWriter();
    new ObjectMapper().writerWithDefaultPrettyPrinter().writeValue(out, inputData);
    String json = out.toString();

    //Output JSON string
    System.out.println("***** Mydata → JSON *****");
    System.out.println(json);

    //Parse JSON string in Jackson and convert it to a data object
    MyData outputData = new ObjectMapper().readValue(json, MyData.class);

    //Output string representation of object
    System.out.println("***** JSON → Mydata *****");
    System.out.println(outputData);
  }
}

Gradle configuration file

Prepare a configuration file build.gradle for building and running with Gradle.

build.gradle 
plugins {
  id 'java'
  id 'application'
}

group 'org.example'
version '0.0.1'

sourceCompatibility = 11

repositories {
  mavenCentral()
}

dependencies {
  implementation 'com.fasterxml.jackson.core:jackson-databind:2.10.3'
}

application {
  mainClassName = 'com.example.App'
}

Execution result

***** Mydata → JSON *****
{
  "personList" : [ {
    "name" : "Peko",
    "sex" : 0
  }, {
    "name" : "Anubis",
    "sex" : 1
  }, {
    "name" : "Isis",
    "sex" : 2
  }, {
    "name" : "Robot",
    "sex" : 9
  } ]
}
***** JSON → Mydata *****
name=[Peko], sex=[NOT_KNOWN]
name=[Anubis], sex=[MALE]
name=[Isis], sex=[FEMALE]
name=[Robot], sex=[NOT_APPLICABLE]

Reference material

Recommended Posts

Sample code to serialize and deserialize Java Enum enums and JSON in Jackson
Convert Java enum enums and JSON to and from Jackson
Code to escape a JSON string in Java
Sample code to convert List to List <String> in Java Stream
[Java] Convert JSON to Java and Java to JSON-How to use GSON and Jackson-
JSON in Java and Jackson Part 1 Return JSON from the server
Sample code to parse date and time with Java SimpleDateFormat
How to use Java enums (Enum) in MyBatis Mapper XML
Java code sample to acquire and display DBLINK source and destination data in Oracle Database using DBLINK
Java 9 new features and sample code
[Android] Convert Map to JSON using GSON in Kotlin and Java
Sample code to call the Yahoo! Local Search API in Java
Sample to read and write LibreOffice Calc fods file in Java 2021
Sample to unzip gz file in Java
Java to C and C to Java in Android Studio
How to assemble JSON directly in Jackson
Discrimination of Enums in Java 7 and above
JSON in Java and Jackson Part ③ Embed JSON in HTML and use it from JavaScript
Sample code to get key JDBC type values in Java + H2 Database
[Java] Output the result of ffprobe -show_streams in JSON and map it to an object with Jackson
Java sample code 02
Java sample code 03
[Java] Convert DB code to code value using enum
JSON with Java and Jackson Part 2 XSS measures
Java sample code 04
Jackson is unable to JSON serialize hibernateLazyInitializer in Spring Data JPA with error
[Java] How to substitute Model Mapper in Jackson
Java sample code 01
Sample code to get the values of major SQL types in Java + MySQL 8.0
Code to use when you want to process Json with only standard library in Java
[For beginners] Minimum sample to display RecyclerView in Java
How to serialize and deserialize LocalDateTime type with GSON
Java classes and instances to understand in the figure
How to convert A to a and a to A using AND and OR in Java
Reverse Enum constants from strings and values in Java
Gzip-compress byte array in Java and output to file
Read JSON in Java
POST JSON in Java
Create JSON in Java
Sample code to get the values of major SQL types in Java + Oracle Database 12c
How to specify character code and line feed code in JAXB
[Java] Change language and locale to English in JVM options
Java source sample (Oracle Database + java) to SELECT and display CLOBs
How to set character code and line feed code in Eclipse
[jackson] I want to receive JSON values "0" and "1" as boolean
What happened in "Java 8 to Java 11" and how to build an environment
How to call and use API in Java (Spring Boot)
[Java] [jackson] Corresponds to the trailing comma (trailing comma) when parsing JSON.
Create API to send and receive Json data in Spring
Things to be aware of when writing code in Java
Correct the character code in Java and read from the URL
Reasons to use Servlet and JSP separately in Java development
Define abstract methods in Java enum and write each behavior
How to develop and register a Sota app in Java
Differences in how to handle strings between Java and Perl
Evolutions of enums and switch statements! ?? Try to achieve algebraic data types and pattern matching in Java
[Java] JSON communication with jackson
Digital signature sample code (JAVA)
Java parallelization code sample collection
Refer to enum in Thymeleaf
Enum Strategy pattern in Java