Convert JSON and YAML in Java (using Jackson and SnakeYAML)

Overview

--Convert JSON and YAML in Java (using Jackson and SnakeYAML) --Jazz to convert JSON to Java object and SnakeYAML to convert Java object to YAML --SnakeYAML to convert YAML to Java objects and Jackson to convert Java objects to JSON --Environment: Java 15 (AdoptOpenJDK 15 + 36) + Jackson Databind 2.11.3 + ShakeYAML 1.27 + Gradle 6.6.1

Build build environment / execution environment with Gradle

Prepare the following build.gradle.

plugins {
  id 'java'
}

repositories {
  mavenCentral()
}

dependencies {
  //Use Jackson Databind
  implementation 'com.fasterxml.jackson.core:jackson-databind:2.11.3'

  //Use ShakeYAML
  implementation 'org.yaml:snakeyaml:1.27'
}

//Define a task that runs the JsonToYaml class
task jsonToYaml(type: JavaExec) {
  main = 'JsonToYaml'
  classpath = sourceSets.main.runtimeClasspath
}

//Define a task that runs the YamlToJson class
task yamlToJson(type: JavaExec) {
  main = 'YamlToJson'
  classpath = sourceSets.main.runtimeClasspath
}

Prepare a class to output the contents of Java object

In order to understand the data structure and class when JSON or YAML is converted to Java object, prepare a class that outputs the object information.

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

/**
 *Output the contents of Java objects derived from JSON or YAML.
 */
public class ObjectDumper {

  private static final int INDENT = 2;

  public static String dump(Map<String, Object> obj) {
    List<String> buffer = new ArrayList<String>();
    dumpMap(obj, 0, buffer);
    return String.join("\n", buffer);
  }

  private static void dumpMap(Map<String, Object> obj, int depth, List<String> buffer) {
    for (Map.Entry<String, Object> entry : obj.entrySet()) {
      Object value = entry.getValue();
      if (value instanceof List) {
        buffer.add(line(entry.getKey(), value, depth));
        dumpList((List<Object>) value, depth + 1, buffer);
      } else if (value instanceof Map) {
        buffer.add(line(entry.getKey(), value, depth));
        dumpMap((Map<String, Object>) value, depth + 1, buffer);
      } else {
        buffer.add(line(entry.getKey(), value, depth));
      }
    }
  }

  private static void dumpList(List<Object> array, int depth, List<String> buffer) {
    for (Object element : array) {
      if (element instanceof List) {
        buffer.add(line(element, depth));
        dumpList((List<Object>) element, depth + 1, buffer);
      } else if (element instanceof Map) {
        buffer.add(line(element, depth));
        dumpMap((Map<String, Object>) element, depth + 1, buffer);
      } else {
        buffer.add(line(element, depth));
      }
    }
  }

  private static String line(String key, Object value, int depth) {
    if (value == null) {
      return " ".repeat(INDENT * depth) + key + ": " + "null";
    } else if (value instanceof Map) {
      return " ".repeat(INDENT * depth) + key + ": " + "(" + value.getClass().getName() + ")";
    } else if (value instanceof List) {
      return " ".repeat(INDENT * depth) + key + ": " + "(" + value.getClass().getName() + ")";
    } else {
      return " ".repeat(INDENT * depth) + key + ": " + value.toString() + " (" + value.getClass().getName() + ")";
    }
  }

  private static String line(Object value, int depth) {
    if (value == null) {
      return " ".repeat(INDENT * depth) + "null";
    } else if (value instanceof Map) {
      return " ".repeat(INDENT * depth) + "(" + value.getClass().getName() + ")";
    } else if (value instanceof List) {
      return " ".repeat(INDENT * depth) + "(" + value.getClass().getName() + ")";
    } else {
      return " ".repeat(INDENT * depth) + value.toString() + " (" + value.getClass().getName() + ")";
    }
  }
}

Convert JSON to YAML

Convert with Jackson: JSON → Java object Convert with SnakeYAML: Java Object → YAML

Source code

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;

import java.util.Map;

public class JsonToYaml {

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

    //JSON string
    String json = """
      {
        "key": "value",
        "foo": "bar",
        "hoge": "fuga",
        "datalist": [
          {
            "string": "mojiretu",
            "integer": 123456,
            "decimal": 123.456,
            "boolean": true,
            "date": "2020-01-01",
            "timestamp": "2020-01-01T00:00:00.123456789+09:00",
            "nullonly": null,
            "object": {"hoge": "HOGE", "fuga": "FUGA"},
            "array": ["foo", "bar", "baz", ["spam", "ham", "eggs"]]
          },
          {
            "string": "String",
            "integer": 100000,
            "decimal": 999.999,
            "boolean": false,
            "date": "2020-01-01",
            "timestamp": "2020-01-01T00:00:00.123456789+09:00",
            "nullonly": null,
            "object": {"hoge": "Hoge", "fuga": "Fuga"},
            "array": ["Huh", "Bah", "Bazu", ["spam", "Ham", "Egg"]]
          }
        ]
      }
      """;
    System.out.println("**********JSON string to enter**********");
    System.out.println(json);

    System.out.println("**********Convert JSON to Java object**********");
    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> obj = mapper.readValue(json, new TypeReference<Map<String, Object>>() {
    });
    System.out.println(ObjectDumper.dump(obj));

    System.out.println("**********Convert Java objects to YAML**********");
    DumperOptions opts = new DumperOptions();
    opts.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
    String yaml = new Yaml(opts).dump(obj);
    System.out.println(yaml);
  }
}

Execution result

**********JSON string to enter**********
{
  "key": "value",
  "foo": "bar",
  "hoge": "fuga",
  "datalist": [
    {
      "string": "mojiretu",
      "integer": 123456,
      "decimal": 123.456,
      "boolean": true,
      "date": "2020-01-01",
      "timestamp": "2020-01-01T00:00:00.123456789+09:00",
      "nullonly": null,
      "object": {"hoge": "HOGE", "fuga": "FUGA"},
      "array": ["foo", "bar", "baz", ["spam", "ham", "eggs"]]
    },
    {
      "string": "String",
      "integer": 100000,
      "decimal": 999.999,
      "boolean": false,
      "date": "2020-01-01",
      "timestamp": "2020-01-01T00:00:00.123456789+09:00",
      "nullonly": null,
      "object": {"hoge": "Hoge", "fuga": "Fuga"},
      "array": ["Huh", "Bah", "Bazu", ["spam", "Ham", "Egg"]]
    }
  ]
}

**********Convert JSON to Java object**********
key: value (java.lang.String)
foo: bar (java.lang.String)
hoge: fuga (java.lang.String)
datalist: (java.util.ArrayList)
  (java.util.LinkedHashMap)
    string: mojiretu (java.lang.String)
    integer: 123456 (java.lang.Integer)
    decimal: 123.456 (java.lang.Double)
    boolean: true (java.lang.Boolean)
    date: 2020-01-01 (java.lang.String)
    timestamp: 2020-01-01T00:00:00.123456789+09:00 (java.lang.String)
    nullonly: null
    object: (java.util.LinkedHashMap)
      hoge: HOGE (java.lang.String)
      fuga: FUGA (java.lang.String)
    array: (java.util.ArrayList)
      foo (java.lang.String)
      bar (java.lang.String)
      baz (java.lang.String)
      (java.util.ArrayList)
        spam (java.lang.String)
        ham (java.lang.String)
        eggs (java.lang.String)
  (java.util.LinkedHashMap)
    string:String(java.lang.String)
    integer: 100000 (java.lang.Integer)
    decimal: 999.999 (java.lang.Double)
    boolean: false (java.lang.Boolean)
    date: 2020-01-01 (java.lang.String)
    timestamp: 2020-01-01T00:00:00.123456789+09:00 (java.lang.String)
    nullonly: null
    object: (java.util.LinkedHashMap)
      hoge:Hoge(java.lang.String)
      fuga:Fuga(java.lang.String)
    array: (java.util.ArrayList)
Huh(java.lang.String)
Bah(java.lang.String)
Bazu(java.lang.String)
      (java.util.ArrayList)
spam(java.lang.String)
Ham(java.lang.String)
Egg(java.lang.String)
**********Convert Java objects to YAML**********
key: value
foo: bar
hoge: fuga
datalist:
- string: mojiretu
  integer: 123456
  decimal: 123.456
  boolean: true
  date: '2020-01-01'
  timestamp: '2020-01-01T00:00:00.123456789+09:00'
  nullonly: null
  object:
    hoge: HOGE
    fuga: FUGA
  array:
  - foo
  - bar
  - baz
  - - spam
    - ham
    - eggs
- string:String
  integer: 100000
  decimal: 999.999
  boolean: false
  date: '2020-01-01'
  timestamp: '2020-01-01T00:00:00.123456789+09:00'
  nullonly: null
  object:
    hoge:Hoge
    fuga:Fuga
  array:
  -Huh
  -Bah
  -Bazu
  - -spam
    -Ham
    -Egg

Convert YAML to JSON

Convert with SnakeYAML: YAML → Java object Convert in Jackson: Java Object → JSON

Source code

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.yaml.snakeyaml.Yaml;

import java.util.Map;

public class YamlToJson {

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

    //YAML string
    String yaml = """
      key: value
      foo: bar
      hoge: fuga
      datalist:
      - string: mojiretu
        integer: 123456
        decimal: 123.456
        boolean: true
        date: 2020-01-01
        timestamp: 2020-01-01T00:00:00.123456789+09:00
        nullonly: null
        object:
          hoge: HOGE
          fuga: FUGA
        array:
        - foo
        - bar
        - baz
        - - spam
          - ham
          - eggs
      - string:String
        integer: 100000
        decimal: 999.999
        boolean: false
        date: 2020-01-01
        timestamp: 2020-01-01T00:00:00.123456789+09:00
        nullonly: null
        object:
          hoge:Hoge
          fuga:Fuga
        array:
        -Huh
        -Bah
        -Bazu
        - -spam
          -Ham
          -Egg
      """;
    System.out.println("**********YAML string to enter**********");
    System.out.println(yaml);

    System.out.println("**********Convert YAML to Java object**********");
    Map<String, Object> obj = new Yaml().load(yaml);
    System.out.println(ObjectDumper.dump(obj));

    System.out.println("**********Convert Java objects to JSON**********");
    ObjectMapper mapper = new ObjectMapper();
    String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
    System.out.println(json);
  }
}

Execution result

**********YAML string to enter**********
key: value
foo: bar
hoge: fuga
datalist:
- string: mojiretu
  integer: 123456
  decimal: 123.456
  boolean: true
  date: 2020-01-01
  timestamp: 2020-01-01T00:00:00.123456789+09:00
  nullonly: null
  object:
    hoge: HOGE
    fuga: FUGA
  array:
  - foo
  - bar
  - baz
  - - spam
    - ham
    - eggs
- string:String
  integer: 100000
  decimal: 999.999
  boolean: false
  date: 2020-01-01
  timestamp: 2020-01-01T00:00:00.123456789+09:00
  nullonly: null
  object:
    hoge:Hoge
    fuga:Fuga
  array:
  -Huh
  -Bah
  -Bazu
  - -spam
    -Ham
    -Egg

**********Convert YAML to Java object**********
key: value (java.lang.String)
foo: bar (java.lang.String)
hoge: fuga (java.lang.String)
datalist: (java.util.ArrayList)
  (java.util.LinkedHashMap)
    string: mojiretu (java.lang.String)
    integer: 123456 (java.lang.Integer)
    decimal: 123.456 (java.lang.Double)
    boolean: true (java.lang.Boolean)
    date: Wed Jan 01 09:00:00 JST 2020 (java.util.Date)
    timestamp: Wed Jan 01 00:00:00 JST 2020 (java.util.Date)
    nullonly: null
    object: (java.util.LinkedHashMap)
      hoge: HOGE (java.lang.String)
      fuga: FUGA (java.lang.String)
    array: (java.util.ArrayList)
      foo (java.lang.String)
      bar (java.lang.String)
      baz (java.lang.String)
      (java.util.ArrayList)
        spam (java.lang.String)
        ham (java.lang.String)
        eggs (java.lang.String)
  (java.util.LinkedHashMap)
    string:String(java.lang.String)
    integer: 100000 (java.lang.Integer)
    decimal: 999.999 (java.lang.Double)
    boolean: false (java.lang.Boolean)
    date: Wed Jan 01 09:00:00 JST 2020 (java.util.Date)
    timestamp: Wed Jan 01 00:00:00 JST 2020 (java.util.Date)
    nullonly: null
    object: (java.util.LinkedHashMap)
      hoge:Hoge(java.lang.String)
      fuga:Fuga(java.lang.String)
    array: (java.util.ArrayList)
Huh(java.lang.String)
Bah(java.lang.String)
Bazu(java.lang.String)
      (java.util.ArrayList)
spam(java.lang.String)
Ham(java.lang.String)
Egg(java.lang.String)
**********Convert Java objects to JSON**********
{
  "key" : "value",
  "foo" : "bar",
  "hoge" : "fuga",
  "datalist" : [ {
    "string" : "mojiretu",
    "integer" : 123456,
    "decimal" : 123.456,
    "boolean" : true,
    "date" : 1577836800000,
    "timestamp" : 1577804400123,
    "nullonly" : null,
    "object" : {
      "hoge" : "HOGE",
      "fuga" : "FUGA"
    },
    "array" : [ "foo", "bar", "baz", [ "spam", "ham", "eggs" ] ]
  }, {
    "string" : "String",
    "integer" : 100000,
    "decimal" : 999.999,
    "boolean" : false,
    "date" : 1577836800000,
    "timestamp" : 1577804400123,
    "nullonly" : null,
    "object" : {
      "hoge" : "Hoge",
      "fuga" : "Fuga"
    },
    "array" : [ "Huh", "Bah", "Bazu", [ "spam", "Ham", "Egg" ] ]
  } ]
}

Reference material

JSON + Jackson

YAML + SnakeYAML

Recommended Posts

Convert JSON and YAML in Java (using Jackson and SnakeYAML)
[Android] Convert Map to JSON using GSON in Kotlin and Java
Convert Java enum enums and JSON to and from Jackson
How to convert A to a and a to A using AND and OR in Java
[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
Try using JSON format API in Java
JSON in Java and Jackson Part ③ Embed JSON in HTML and use it from JavaScript
Sample code to serialize and deserialize Java Enum enums and JSON in Jackson
Parse and objectize JSON using the @JsonProperty annotation of the Java library Jackson
JSON with Java and Jackson Part 2 XSS measures
Read JSON in Java
POST JSON in Java
Create JSON in Java
Mutual conversion between Java objects and JSON using Moshi
Try using RocksDB in Java
[Java] JSON communication with jackson
POST Json in Java ~ HttpURLConnection ~
Json serialization / deserialization in Java 1.4
Implement Thread in Java and try using anonymous class, lambda
Tips for using Salesforce SOAP and Bulk API in Java
Encoding and Decoding example in Java
Encrypt using RSA cryptography in Java
How to POST JSON in Java-Method using OkHttp3 and method using HttpUrlConnection-
StringBuffer and StringBuilder Class in Java
Understanding equals and hashCode in Java
HTTPS connection using tls1.2 in Java 6
I tried using JWT in Java
Hello world in Java and Gradle
[Java] Output the result of ffprobe -show_streams in JSON and map it to an object with Jackson
Creating a project (and GitHub repository) using Java and Gradle in IntelliJ IDEA
I tried using Elasticsearch API in Java
Convert Java org.w3c.dom.Document objects and XML strings
Difference between final and Immutable in Java
Using Hystrix and Sentinel in code example
Try using the Stream API in Java
Map without using an array in java
[Java] for Each and sorted in Lambda
Using JavaScript from Java in Rhino 2021 version
ERRORCODE = -4471 occurs in Java application using Db2.
Convert SVG files to PNG files in Java
Read Felica using RC-S380 (PaSoRi) in Java
Java and Derby integration using JDBC (using NetBeans)
Arrylist and linked list difference in java
Working with huge JSON in Java Lambda
Program PDF headers and footers in Java
Learn Flyweight patterns and ConcurrentHashMap in Java
Java Direction in C ++ Design and Evolution
Java to C and C to Java in Android Studio
Reading and writing gzip files in Java
Difference between int and Integer in Java
How to assemble JSON directly in Jackson
Discrimination of Enums in Java 7 and above
Convert JSON to TSV and TSV to JSON with Ruby
Notes on implementing google books api in java okhttp and gson versions and okhttp and jackson versions
NLP4J [004] Try text analysis using natural language processing and parsing statistical processing in Java
Impressions and doubts about using java for the first time in Android Studio
NLP4J [003] Try text analysis using natural language processing and part-speech statistical processing in Java
When using a list in Java, java.awt.List comes out and an error occurs
I tried to convert JavaBean and XML with Jackson formatter XML in this era
Be careful with requests and responses when using the Serverless Framework in Java