Total Pageviews

2018/02/12

[Jackson] How to convert JSON string to YAML?

Problem
Assume I have a JSON string:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
{
 "id": 1,
 "name": "Albert",
 "email": "albert@gmail.com",
 "phone": "0900123456",
 "address": {
  "streetAddress": "信義區信義路五段7號",
  "city": "台北市",
  "zipCode": "110"
 }
}


I would like to convert JSON string to YAML:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
 ---
id: 1
name: "Albert"
email: "albert@gmail.com"
phone: "0900123456"
address:
  streetAddress: "信義區信義路五段7號"
  city: "台北市"
  zipCode: "110"
 



How to do it?

How-To
Take advantage of libraries can fulfill this requirement.

Add the following dependencies in pom.xml
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 <dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-core</artifactId>
  <version>2.9.3</version>
 </dependency>

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

 <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-annotations</artifactId>
  <version>2.9.3</version>
 </dependency>

 <dependency>
  <groupId>com.fasterxml.jackson.dataformat</groupId>
  <artifactId>jackson-dataformat-yaml</artifactId>
  <version>2.9.3</version>
 </dependency>

Here has sample code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
  package test.albert.jackson;
  
  import java.io.IOException;
  
  import com.fasterxml.jackson.databind.JsonNode;
  import com.fasterxml.jackson.databind.ObjectMapper;
  import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;
  
  import lombok.extern.slf4j.Slf4j;
  
  @Slf4j
  public class JacksonTest {
  
      public static void main(String[] args) throws IOException {
          Address address = Address.builder().zipCode("110").city("台北市").streetAddress("信義區信義路五段7號").build();
          Employee albert = Employee.builder().id(1).name("Albert").email("albert@gmail.com").phone("0900123456")
                  .address(address).build();
  
          
          ObjectMapper mapper = new ObjectMapper();
          
          // convert object to JSON
          String json = mapper.writeValueAsString(albert);
          log.debug(json);
          
          // convert JSON to YAML
          JsonNode jsonNode = mapper.readTree(json);
          String yaml = new YAMLMapper().writeValueAsString(jsonNode);
          log.debug("yaml = \n " + yaml);
      }
  
  }



No comments: