In today's blog, we will see about JSON, YAML, and Java object conversion.
We will convert YAML -> JSON -> Java POJO and also reverse conversion Java POJO -> JSON -> YAML.
What is YAML?
YAML is a data serialization language that is commonly used to write configuration files. YAML stands for yet another markup language. YAML isn't a markup language (a recursive acronym) which indicates that YAML is for data, not for documents.
Maven dependencies
Jackson is a popular Java-based library for parsing and manipulating JSON and XML files.Jackson-datatype JSR contains the module that helps Jackson in java (data and time) data type
snakeYAML is a java library that helps to read YAML files and allows us to parse and convert YAML to java objects
Add the below dependencies in pom.xml
<!-- Jackson -->
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.6.0</version>
</dependency>
<!-- Yaml -->
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
</dependency>
Conversion of YAML to JSON
We will read employee details from the below YAML file.Now we have to create an ObjectMapper and YAMLFactory instance. The ObjectMapper takes a YAMLFactory instance in its constructor.
Below is the YAML file content that we will convert to equivalent JSON content.
id: 1201
name: kumar
address:
streeName: Dev alone 404
pincode: 600001
currentSalary: 25000
joinedDate: '2021-11-21'
skils:
- Java
- Spring Boot
- SQL
The below Java method will take YAML content and convert it to JSON using the ObjectMapper class.
public String covertYamlToJson(String filename) throws IOException {
YAMLFactory factory = new YAMLFactory();
ObjectMapper yamlToJsonmapper = new ObjectMapper(factory);
yamlToJsonmapper.setSerializationInclusion(Include.NON_NULL).registerModule(new JavaTimeModule())
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
Object jsonObject = yamlToJsonmapper.readValue(filename, Object.class);
String jsonContent = new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject);
return jsonContent;
}
The writerWithDefaultPrettyPrinter helps to format or indent the JSON and writeValueAsString return the JSON as the string.
{
"id": 1201,
"name": "kumar",
"address": {
"streeName": "Dev alone 404",
"pincode": 600001
},
"currentSalary": 25000,
"joinedDate": "2021-11-21",
"skils": [
"Java",
"Spring Boot",
"SQL"
]
}
Conversion of JSON to JAVA POJO
Using Jackson ObjectMapper we can convert the JSON string value into a java model class.The Include.NON_NULL clause ignores null fields during serialization, and JavaTimeModule supports java (date and time) datatypes.
Create POJO class which will be used in JSON to object conversion. Below is the java generic method it takes generic class type and file content since it takes generic class type it will return generic object based on our class type and convert the file content to the class.
import java.time.LocalDate;
import java.util.List;
public class Employee {
public int id;
public String name;
public Address address;
public double currentSalary;
public LocalDate joinedDate;
public List<String> skils;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public double getCurrentSalary() {
return currentSalary;
}
public void setCurrentSalary(double currentSalary) {
this.currentSalary = currentSalary;
}
public LocalDate getJoinedDate() {
return joinedDate;
}
public void setJoinedDate(LocalDate joinedDate) {
this.joinedDate = joinedDate;
}
public List<String> getSkils() {
return skils;
}
public void setSkils(List<String> skils) {
this.skils = skils;
}
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", address=" + address + ", currentSalary=" + currentSalary +
", joinedDate=" + joinedDate + ", skils=" + skils + "]";
}
}
class Address {
public String streeName;
public int pincode;
public String getStreeName() {
return streeName;
}
public void setStreeName(String streeName) {
this.streeName = streeName;
}
public int getPincode() {
return pincode;
}
public void setPincode(int pincode) {
this.pincode = pincode;
}
}
public<T> T covertJsonToObject(String content, Class<T> objectType) throws IOException {
ObjectMapper yamlToJsonmapper = new ObjectMapper();
yamlToJsonmapper.setSerializationInclusion(Include.NON_NULL).registerModule(new JavaTimeModule())
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
return yamlToJsonmapper.readValue(content, objectType);
}
Reverse Conversion
Now we will do the reverse conversion of java POJO to JSON to YAML.
public String covertObjectToJson(Object object) throws IOException {
ObjectMapper yamlToJsonmapper = new ObjectMapper();
yamlToJsonmapper.setSerializationInclusion(Include.NON_NULL).registerModule(new JavaTimeModule())
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
String objectJSON = yamlToJsonmapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
return objectJSON;
}
public String convertJsonTOYaml(String jsonString) throws IOException {
ObjectMapper yamlToJsonmapper = new ObjectMapper();
yamlToJsonmapper.setSerializationInclusion(Include.NON_NULL).registerModule(new JavaTimeModule())
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
JsonNode jsonNodeTree = yamlToJsonmapper.readTree(jsonString);
String jsonAsYaml = new YAMLMapper().writeValueAsString(jsonNodeTree);
return jsonAsYaml;
}
Writing to a File
Sometimes we may need to write our YAML or JSON content to an external file. The below code is used to file content to file if the file doesn't exist then it creates a file, if the file is already present it will update the file content.
public void writeToFile(String fileName, String fileContent) throws IOException {
Files.write(Paths.get(fileName), fileContent.getBytes());
}
Reading From File
public String readFile(String fileName) throws IOException {
String fileContent = Files.readString(Paths.get(fileName), StandardCharsets.UTF_8);
return fileContent;
}