Jackson Object Mapper Examples
ObjectMapper provides functionality for reading and writing JSON, either to and from basic POJOs (Plain Old Java Objects) or to and from a general-purpose JSON Tree Model (JsonNode), as well as related functionality for performing conversions.
It is also highly customizable to work both with different styles of JSON content and to support more advanced Object concepts such as polymorphism and Object identity.
ObjectMapper also serves as a base for advanced ObjectReader and ObjectWriter classes. Mapper (and ObjectReaders, ObjectWriters it constructs) will use instances of JsonParser and JsonGenerator for implementing actual reading/writing of JSON.
The some of the functionality of ObjectMapper is only exposed via ObjectReader and ObjectWriter: specifically, reading/writing of longer sequences of values is only available through ObjectReader.readValues(InputStream) and ObjectWriter.writeValues(OutputStream).
To use object mapper in java we need to add a dependency from maven to pom.xml file as
com.fasterxml.jackson.core
jackson-core
2.11.0
We need to create instance of ObjectMapper
ObjectMapper mapper = new ObjectMapper();
Object value = mapper.readValue(jsonSource , Object .class);
Suppose we have order JSON
{
"id": "Abcd000190",
"customerId": "sshfkdhd",
"amount": 5600.00,
"status": "confirmed"
}
and we want to map this JSON to the object for our internal operations then.
1). Convert JSON object to Java object
How to convert JSON string to a custom object in java?
we have a POJO class
class Order {
private String id;
private String customerId;
private double amount;
private String status;
//@Getter @Setter @toString
}
public class JsontoObjectMapping {
public static void main(String args[]) {
String jsonStr = "{ \"id\" : \"10009\", \"customerId\" : \"sshfkdhd\",\"amount\" : \"5600.00\", \"status\" : \"confirmed\ }";
ObjectMapper mapper = new ObjectMapper();
Order order = mapper.readValue(jsonSource, Order.class);
System.out.println(order);
}
}
output:
Order[ id = 10009 , customerId = sshfkdhd , amount = 5600.00 , status = confirmed]
If you have file JSON then
C:\\files\\order.json";
{
"id": "Abcd000190",
"customerId": "sshfkdhd",
"amount": 5600.00,
"status": "confirmed"
}
public class FileJsonToObject {
public static void main(String args[]) {
String filePath = "C:\\files\\order.json";
ObjectMapper mapper = new ObjectMapper();
try {
Order order = objectMapper.readValue(new File(filePath), Order.class);
System.out.println(order);
} catch (JsonGenerationException ex)
{
System.out.println("Exception : "=+ex +" occured during FileJsonToObject conversion.");
} catch (JsonMappingException ex)
{
System.out.println("Exception : "=+ex +" occured during FileJsonToObject conversion.");
} catch (IOException ex)
{
System.out.println("Exception : "=+ex +" occured during SerializeObject conversion.");
}
}
}
2). Java Object to JSON
Converting java object to JSON file is pretty simple
public class JavaObjecToJsonFile {
public static void main(String args[]) {
ObjectMapper objectMapper = new ObjectMapper();
Order order = new Order("10009", "sshfkdhd", 5600.00, "confirmed");
try {
objectMapper.writeValue(new File("C:\\order-files\\order.json"), order);
System.out.println(order);
} catch (JsonGenerationException ex)
{
System.out.println("Exception : "=+ex +" occured during JavaObjecToJsonFile conversion.");
} catch (JsonMappingException ex)
{
System.out.println("Exception : "=+ex +" occured during JavaObjecToJsonFile conversion.");
} catch (IOException ex)
{
System.out.println("Exception : "=+ex +" occured during JavaObjecToJsonFile conversion.");
}
}
}
The output of the above in the file will be:
order.json";
{
"id": "Abcd000190",
"customerId": "sshfkdhd",
"amount": 5600.00,
"status": "confirmed"
}
3). Serialize JSON object in java
To communicate between different MicroServices, We need to send data from one MicroService, to other MicroService. ObjectMapper do it for us. It Parse java object to json string or byte array which can be sent over network.
How to convert java object to JSON string?
ObjectMapper class has methods writeValueAsString and writeValueAsBytes which generates a JSON from a Java object and returns the generated JSON as a string or as a byte array.
class Order implements Serializable {
private String id;
private String customerId;
private double amount;
private String status;
//@Getter @Setter @toString
}
public class SerializeObject {
public static void main(String args[]) {
ObjectMapper objectMapper = new ObjectMapper();
Order order = new Order("10009", "sshfkdhd", 5600.00, "confirmed");
try {
String orderString = objectMapper.writeValueAsString(order);
} catch (JsonGenerationException ex)
{
System.out.println("Exception : "=+ex +" occured during SerializeObject.");
} catch (JsonMappingException ex)
{
System.out.println("Exception : "=+ex +" occured during SerializeObject.");
} catch (IOException ex)
{
System.out.println("Exception : "=+ex +" occured during SerializeObject.");
}
}
}
4). Creating Java Map from JSON String
Sometimes we need to map json string to Map object ,Using ObjectMapper we can parse A JSON into a Java Map.
String orderJson = "{ \"id\" : \"10009\", \"customerId\" : \"sshfkdhd\",\"amount\" : \"5600.00\", \"status\" : \"confirmed\ }";
ObjectMapper objectMapper = new ObjectMapper();
try {
Map<String, Object> map = objectMapper.readValue(orderJson, new TypeReference<Map<String,Object> >(){});
} catch (JsonGenerationException ex)
{
System.out.println("Exception : "=+ex +" occured during SerializeObject.");
} catch (JsonMappingException ex)
{
System.out.println("Exception : "=+ex +" occured during SerializeObject.");
} catch (IOException ex)
{
System.out.println("Exception : "=+ex +" occured during SerializeObject.");
}
5). Creating a Java List from a JSON Array String
Sometimes we need to Creating a Java List from a JSON Array ,Using ObjectMapper we can convert a JSON Array String into a Java List.
How to get a list from JSON object in java?
String jsonArray =
"["{ \"id\" : \"10009\", \"customerId\" : \"sshfkdhd\",\"amount\" : \"5600.00\", \"status\" : \"confirmed\ },"{ \"id\" : \"10011\", \"customerId\" : \"abcd0001\",\"amount\" : \"4390.00\", \"status\" : \"pending\ }]";
ObjectMapper objectMapper = new ObjectMapper();
try {
List<Order> orders = objectMapper.readValue(jsonArray, new TypeReference<List<Order>>(){});
} catch (JsonGenerationException ex)
{
System.out.println("Exception : "=+ex +" occured during SerializeObject.");
} catch (JsonMappingException ex)
{
System.out.println("Exception : "=+ex +" occured during SerializeObject.");
} catch (IOException ex)
{
System.out.println("Exception : "=+ex +" occured during SerializeObject.");
}
In this article, we have seen Jackson Object Mapper Examples.
0 Comments
Post a Comment