Using TomlMapper#readValue method, we can get a Java object from TOML string.
Example
Employee deserializedEmp = tomlMapper.readValue(tomlStr, Employee.class);
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;
}
@Override
public String toString() {
return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]";
}
}
TomlToObject.java
package com.sample.app;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.dataformat.toml.TomlMapper;
import com.sample.app.dto.Employee;
public class TomlToObject {
public static void main(String[] args) throws JsonMappingException, JsonProcessingException {
String tomlStr = "id = 1\n"
+ "firstName = 'Rama Devi'\n"
+ "lastName = 'G'\n";
TomlMapper tomlMapper = new TomlMapper();
Employee deserializedEmp = tomlMapper.readValue(tomlStr, Employee.class);
System.out.println(deserializedEmp);
}
}
Output
Employee [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>
Previous Next Home
No comments:
Post a Comment