Step 1: Get an instance of TomlMapper.
TomlMapper mapper = new TomlMapper();
Step 2: Serialize java object to string using writeValueAsString method.
String toml = mapper.writeValueAsString(emp);
Find the below working application.
Employee.java
package com.sample.app.dto;
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;
}
}
ObjectToToml.java
package com.sample.app;
import java.io.IOException;
import com.fasterxml.jackson.dataformat.toml.TomlMapper;
import com.sample.app.dto.Employee;
public class ObjectToToml {
public static void main(String[] args) throws IOException {
TomlMapper mapper = new TomlMapper();
Employee emp = new Employee();
emp.setId(1);
emp.setFirstName("Rama Devi");
emp.setLastName("G");
String toml = mapper.writeValueAsString(emp);
System.out.println(toml);
}
}
Output
id = 1 firstName = 'Rama Devi' lastName = 'G'
Dependency used
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-toml</artifactId>
<version>2.13.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.13.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.13.4</version>
</dependency>
</dependencies>
No comments:
Post a Comment