Using JSON, Object Mapper and Model Mapper

Suppose there is one input JSON which is mapped with an Employee.java class as below:

package com.test;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated(“org.jsonschema2pojo”)
@JsonPropertyOrder({ “id”, “firstName”, “lastName” })
public class Employee {
@JsonProperty(“id”)
private Integer id;
@JsonProperty(“firstName”)
private String firstName;
@JsonProperty(“lastName”)
private String lastName;
@JsonProperty(“start”)
private Start start;
@JsonProperty(“end”)
private End end;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
*
* @return The id
*/
@JsonProperty(“id”)
public Integer getId() {
return id;
}
/**
*
* @param id
* The id
*/
@JsonProperty(“id”)
public void setId(Integer id) {
this.id = id;
}
/**
*
* @return The firstName
*/
@JsonProperty(“firstName”)
public String getFirstName() {
return firstName;
}
/**
*
* @param firstName
* The firstName
*/
@JsonProperty(“firstName”)
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
*
* @return The lastName
*/
@JsonProperty(“lastName”)
public String getLastName() {
return lastName;
}
/**
*
* @param lastName
* The lastName
*/
@JsonProperty(“lastName”)
public void setLastName(String lastName) {
this.lastName = lastName;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
public Start getStart() {
return start;
}
public void setStart(Start start) {
this.start = start;
}
public End getEnd() {
return end;
}
public void setEnd(End end) {
this.end = end;
}
public void setAdditionalProperties(Map<String, Object> additionalProperties) {
this.additionalProperties = additionalProperties;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return “Employee values: ” + “id: ” + id + “, firstname: ” + firstName + “, lastname: ” + lastName
+ “, start-date: ” + start.getDateTime() + “, start-time” + start.getTimeZone() + “, end-date: “
+ end.getDateTime() + “, end-time: ” + end.getTimeZone();
}
}

The fields Start and End are separate classes which are defined as below:

Start Class:

package com.test;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(Include.NON_NULL)
public class Start {

@JsonProperty(“dateTime”)
private String dateTime;

@JsonProperty(“timeZone”)
private String timeZone;

public String getDateTime() {
return dateTime;
}
public void setDateTime(String dateTime) {
this.dateTime = dateTime;
}
public String getTimeZone() {
return timeZone;
}
public void setTimeZone(String timeZone) {
this.timeZone = timeZone;
}

End Class:

package com.test;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(Include.NON_NULL)
public class End {

@JsonProperty(“dateTime”)
private String dateTime;

@JsonProperty(“timeZone”)
private String timeZone;

public String getDateTime() {
return dateTime;
}
public void setDateTime(String dateTime) {
this.dateTime = dateTime;
}
public String getTimeZone() {
return timeZone;
}
public void setTimeZone(String timeZone) {
this.timeZone = timeZone;
}

}

 

So far so Good, no issues to map the fields from JSON to the above mentioned Employee class. Now if you create another class with selected fields from the above classes and extirpate the unnecessary fields as mentioned below in the SelectedJSONClass below:

package com.test;
import java.util.Date;
public class SelectedJSONClass {

private String firstName;
private Date startDate;
private Date endDate;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return “Employee values: “+
“firstname: “+ firstName +”,start-date: “+startDate
+”, end-date: “+endDate;
}
}

The problem here is: The fields for startdate and enddate are different in the class and while converting the same from String to Date, there might be some extra code needed to convert. But using ModelMapper this can be done and converted easily, as this is a very powerful jar to convert the models. Below is the sample class which can be used:

package com.test;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.codehaus.jettison.json.JSONObject;
import org.modelmapper.Converter;
import org.modelmapper.ModelMapper;
import org.modelmapper.PropertyMap;
import org.modelmapper.TypeMap;
import org.modelmapper.spi.MappingContext;
import org.omg.CORBA.CTX_RESTRICT_SCOPE;
import com.fasterxml.jackson.databind.ObjectMapper;
public class LoadFromJSON {
public static void main(String args[]) throws Exception {

JSONObject start = new JSONObject();

Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss.SS”);
String strDate = sdf.format(cal.getTime());
System.out.println(“Current date in String Format: “+strDate);

start.put(“dateTime”, strDate);
start.put(“timeZone”, “IST”);

JSONObject end = new JSONObject();
end.put(“dateTime”, strDate);
end.put(“timeZone”, “GMT”);

JSONObject json = new JSONObject();
json.put(“id”, 2);
json.put(“firstName”, “hello”);
json.put(“lastName”, “world”);

json.put(“start”, start);
json.put(“end”, end);

byte[] jsonData = json.toString().getBytes();

ObjectMapper mapper = new ObjectMapper();
Employee employee = mapper.readValue(jsonData, Employee.class);
System.out.println(employee);
ModelMapper model = new ModelMapper();

Converter<String, Date> stringToDate = new Converter<String, Date>() {

@Override
public Date convert(MappingContext<String, Date> arg0) {
SimpleDateFormat sdf1 = new SimpleDateFormat();
sdf1.applyPattern(“yyyy-MM-dd HH:mm:ss.SS”);
Date date =null;
try {
date = sdf1.parse(arg0.getSource().toString());
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
};
model.addConverter(stringToDate);
SelectedJSONClass map = model.map(employee, SelectedJSONClass.class);
System.out.println(employee);
System.out.println(map);

}
}

 

Dependency can be injected using:

<dependency>
  <groupId>org.modelmapper</groupId>
  <artifactId>modelmapper</artifactId>
  <version>1.1.0</version>
</dependency>

Source: http://modelmapper.org/

Author: Debojyoti Mahapatra

Digiprove sealCopyright secured by Digiprove © 2019 Geeks 18

Be the first to comment

Leave a Reply

Your email address will not be published.


*