Sunday, 3 June 2018

Jackson: Convert java object to yaml

Below statements convert java object to yaml string.

ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
mapper.writeValueAsString(obj)

Employee.java
package com.sample.model;

public class Employee {

 private int id;
 private String firstName;
 private String lastName;

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 @Override
 public String toString() {
  return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]";
 }

}

YAMLUtil.java
package com.sample.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import com.fasterxml.jackson.databind.type.MapType;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;

public class YAMLUtil {

 private static ObjectMapper mapper = new ObjectMapper(new YAMLFactory());

 public static void printYAML(Object obj) throws JsonGenerationException, JsonMappingException, IOException {
  mapper.writeValue(System.out, obj);
 }

 public static String getYAML(Object obj) throws JsonProcessingException {
  return mapper.writeValueAsString(obj);
 }

 public static <T> T getObject(String yaml, Class<T> clazz)
   throws JsonParseException, JsonMappingException, IOException {
  return mapper.readValue(yaml, clazz);

 }

 public static <T> List<T> getListOfObjects(String yaml, Class<T> clazz)
   throws JsonParseException, JsonMappingException, IOException {
  CollectionType listType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, clazz);
  List<T> ts = mapper.readValue(yaml, listType);
  return ts;
 }

 public static <K, V> Map<K, V> getMapOfObjects(String yaml, Class<K> keyClazz, Class<V> valueClazz)
   throws JsonParseException, JsonMappingException, IOException {
  TypeFactory typeFactory = mapper.getTypeFactory();
  MapType mapType = typeFactory.constructMapType(HashMap.class, keyClazz, valueClazz);
  return mapper.readValue(yaml, mapType);
 }
}


Test.java
package com.sample.app;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.sample.model.Employee;
import com.sample.util.YAMLUtil;

public class Test {

 public static void main(String args[]) throws JsonProcessingException {
  Employee emp = new Employee();
  emp.setFirstName("Krishna");
  emp.setLastName("Gurram");
  emp.setId(1);

  String yaml = YAMLUtil.getYAML(emp);
  System.out.println(yaml);
 }
}


Output
---
id: 1
firstName: "Krishna"
lastName: "Gurram"







Previous                                                 Next                                                 Home

YAML: Represent multi line strings

There are different ways to write multi line strings in yaml.

Using |
| symbol preserve new lines.

Employee.yml
# YAML file represent employee details
---
id: 1
firstName: "Krishna"
lastName: "Gurram"
aboutMe: |
   Failure never overtake me
   if my determination to succeed is
   strong enough.


After converting above yml to employee object, I printed them.
System.out.println("id : " + emp.getId());
System.out.println("First Name : " + emp.getFirstName());
System.out.println("Last Name: " + emp.getLastName());
System.out.println("About Me : " + emp.getAboutMe());

In console, they are printed like below.

id : 1
First Name : Krishna
Last Name: Gurram
About Me : Failure never overtake me
if my determination to succeed is
strong enough.

Using >
‘>’ character folds the newlines.

employee.yml
# YAML file represent employee details
---
id: 1
firstName: "Krishna"
lastName: "Gurram"
aboutMe: >
   Failure never overtake me
   if my determination to succeed is
   strong enough.

After converting above yml to employee object, I printed them.
System.out.println("id : " + emp.getId());
System.out.println("First Name : " + emp.getFirstName());
System.out.println("Last Name: " + emp.getLastName());
System.out.println("About Me : " + emp.getAboutMe());

In console, they are printed like below.

id : 1
First Name : Krishna
Last Name: Gurram
About Me : Failure never overtake me if my determination to succeed is strong enough.

Find the below working application.

Employee.java
package com.sample.model;

public class Employee {

 private int id;
 private String firstName;
 private String lastName;
 private String aboutMe;

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 public String getAboutMe() {
  return aboutMe;
 }

 public void setAboutMe(String aboutMe) {
  this.aboutMe = aboutMe;
 }

 @Override
 public String toString() {
  return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", aboutMe=" + aboutMe
    + "]";
 }

}

YAMLUtil.java
package com.sample.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;

public class YAMLUtil {

 private static ObjectMapper mapper = new ObjectMapper(new YAMLFactory());

 public static void printYAML(Object obj) throws JsonGenerationException, JsonMappingException, IOException {
  mapper.writeValue(System.out, obj);
 }

 public static <T> T getObject(String yaml, Class<T> clazz)
   throws JsonParseException, JsonMappingException, IOException {
  return mapper.readValue(yaml, clazz);

 }

 public static <T> List<T> getListOfObjects(String yaml, Class<T> clazz)
   throws JsonParseException, JsonMappingException, IOException {
  CollectionType listType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, clazz);
  List<T> ts = mapper.readValue(yaml, listType);
  return ts;

 }
 
}

Test.java
package com.sample.app;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.sample.model.Employee;
import com.sample.util.YAMLUtil;

public class Test {

 private static final String filePath = "C:\\Users\\krishna\\Documents\\Study\\YAML\\yaml files\\employee.yml";

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

  String fileString = new String(Files.readAllBytes(Paths.get(filePath)), StandardCharsets.UTF_8);

  Employee emp = YAMLUtil.getObject(fileString, Employee.class);

  System.out.println("id : " + emp.getId());
  System.out.println("First Name : " + emp.getFirstName());
  System.out.println("Last Name: " + emp.getLastName());
  System.out.println("About Me : " + emp.getAboutMe());

 }
}



Previous                                                 Next                                                 Home

YAML: Reuse a block of code (merging)

The "<<" merge key is used to indicate that all the keys of one or more specified maps should be inserted into the current map

For example, consider below employee instance of the organization ‘ABC labs’.

employee.yml
--- 
firstName: Krishna
id: 1
lastName: MP
organization: 
  city: Bangalore
  organizationName: "ABC labs"

Suppose, you are writing a service that return all the employees in the organisation ‘ABC labs’, it looks like below.
--- 
- 
  firstName: Krishna
  id: 1
  lastName: MP
  organization: 
    city: Bangalore
    organizationName: "ABC labs"
- 
  firstName: Chamu
  id: 2
  lastName: Kb
  organization: 
    city: Bangalore
    organizationName: "ABC labs"
As you observe the above yaml information, ‘organization’ details are repeated here.

YAML provides << (merge key) that is used to reuse the block of information.

For example,

employee.yaml

---
- id: 1
  firstName: "Krishna"
  lastName: "MP"
  organization: &ABCOrg
    organizationName: "ABC labs"
    city: "Bangalore"
- id: 2
  firstName: "Chamu"
  lastName: "Kb"
  <<: *ABCOrg


As you see above example, I created a reference ‘&ABCOrg’ and reused this reference in all the places.

You can test the result at ‘http://www.yamllint.com/’.


When I click on ‘Go’ button, it is changed like below.





Previous                                                 Next                                                 Home

YAML: Define empty array

Just use [] to define an empty array.

Example
emptyArray: []


Employee.java
package com.sample.model;

import java.util.Arrays;

public class Employee {

 private int id;
 private String firstName;
 private String lastName;
 private String[] hobbies;

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 public String[] getHobbies() {
  return hobbies;
 }

 public void setHobbies(String[] hobbies) {
  this.hobbies = hobbies;
 }

 @Override
 public String toString() {
  return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", hobbies="
    + Arrays.toString(hobbies) + "]";
 }

}

YAMLUtil.java
package com.sample.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;

public class YAMLUtil {

 private static ObjectMapper mapper = new ObjectMapper(new YAMLFactory());

 public static void printYAML(Object obj) throws JsonGenerationException, JsonMappingException, IOException {
  mapper.writeValue(System.out, obj);
 }

 public static <T> T getObject(String yaml, Class<T> clazz)
   throws JsonParseException, JsonMappingException, IOException {
  return mapper.readValue(yaml, clazz);

 }

 public static <T> List<T> getListOfObjects(String yaml, Class<T> clazz)
   throws JsonParseException, JsonMappingException, IOException {
  CollectionType listType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, clazz);
  List<T> ts = mapper.readValue(yaml, listType);
  return ts;

 }
 
}


Test.java
package com.sample.app;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.sample.model.Employee;
import com.sample.util.YAMLUtil;

public class Test {

 private static final String filePath = "C:\\Users\\krishna\\Documents\\Study\\YAML\\yaml files\\employee.yml";

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

  String fileString = new String(Files.readAllBytes(Paths.get(filePath)), StandardCharsets.UTF_8);

  Employee emp = YAMLUtil.getObject(fileString, Employee.class);

  System.out.println(emp);

 }
}

Output
Employee [id=1, firstName=Krishna, lastName=Gurram, hobbies=[]]



Previous                                                 Next                                                 Home

YAML: [] : represent list or array members

In my previous post, I explained, how to represent list of members using – symbol. You can also use [] notation to represent list (or) array of objects.



employee.yaml
# YAML file represent employee details
id: 1
firstName: "Krishna"
lastName: "Gurram"
hobbies : ["Chess", "Cricket"]

Employee.java
package com.sample.model;

import java.util.Arrays;

public class Employee {

 private int id;
 private String firstName;
 private String lastName;
 private String[] hobbies;

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 public String[] getHobbies() {
  return hobbies;
 }

 public void setHobbies(String[] hobbies) {
  this.hobbies = hobbies;
 }

 @Override
 public String toString() {
  return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", hobbies="
    + Arrays.toString(hobbies) + "]";
 }

}

YAMLUtil.java

package com.sample.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;

public class YAMLUtil {

 private static ObjectMapper mapper = new ObjectMapper(new YAMLFactory());

 public static void printYAML(Object obj) throws JsonGenerationException, JsonMappingException, IOException {
  mapper.writeValue(System.out, obj);
 }

 public static <T> T getObject(String yaml, Class<T> clazz)
   throws JsonParseException, JsonMappingException, IOException {
  return mapper.readValue(yaml, clazz);

 }

 public static <T> List<T> getListOfObjects(String yaml, Class<T> clazz)
   throws JsonParseException, JsonMappingException, IOException {
  CollectionType listType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, clazz);
  List<T> ts = mapper.readValue(yaml, listType);
  return ts;

 }
 
}

Test.java

package com.sample.app;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.sample.model.Employee;
import com.sample.util.YAMLUtil;

public class Test {

 private static final String filePath = "C:\\Users\\krishna\\Documents\\Study\\YAML\\yaml files\\employee.yml";

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

  String fileString = new String(Files.readAllBytes(Paths.get(filePath)), StandardCharsets.UTF_8);

  Employee emp = YAMLUtil.getObject(fileString, Employee.class);

  System.out.println(emp);

 }
}


Output

Employee [id=1, firstName=Krishna, lastName=Gurram, hobbies=[Chess, Cricket]]


Previous                                                 Next                                                 Home