Following statements are used to convert Employee object to JsonNode.
Employee emp1 = new Employee();
emp1.setFirstName("Krishna");
emp1.setLastName("Gurram");
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.convertValue(emp1, JsonNode.class);
Find the below working application.
Employee.java
package com.sample.app.model;
public class Employee {
private String firstName;
private String lastName;
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;
}
}
App.java
package com.sample.app;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sample.app.model.Employee;
public class App {
public static void main(String args[]) throws JsonProcessingException, IOException {
Employee emp1 = new Employee();
emp1.setFirstName("Krishna");
emp1.setLastName("Gurram");
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.convertValue(emp1, JsonNode.class);
JsonNode firstNameNode = jsonNode.get("firstName");
JsonNode lastNameNode = jsonNode.get("lastName");
System.out.println("First Name : " + firstNameNode.textValue());
System.out.println("Last Name : " + lastNameNode.textValue());
}
}
Output
First Name : Krishna
Last Name : Gurram
No comments:
Post a Comment