Converting Json into a DTO array - java

I have an interesting JSON parsing problem, at least to me since I am doing this for the first time. I have the following sample JSON and I want to map it to equivalent DTOs:
{
"modules":
[
{
"name":"module1",
"shortId":23425,
"pmns":
[
{
"name":"pmn1",
"position":1,
"pmnType":"D3"
},
{
"name":"pmn3",
"position":3,
"pmnType":"R2"
},
{
"name":"pmn7",
"position":5,
"pmnType":"S1"
},
]
},
{
"name":"module2",
"shortId":1572,
"pmns":
[
{
"name":"pmn1",
"position":3,
"pmnType":"D3"
},
{
"name":"pmn12",
"position":35,
"pmnType":"R2"
},
]
}
]
}
This is my ModuleDTO class:
public class ModuleDTO {
private String _name;
private short _shortId;
private PmnDTO[] _pmns;
public String getName() {
return _name;
}
public short getShortId() {
return _shortId;
}
public PmnDTO[] getPmns() {
return _pmns;
}
#JsonProperty("name")
public void setName(String name) {
this._name = name;
}
#JsonProperty("shortId")
public void setShortId(short shortId) {
this._shortId = shortId;
}
#JsonProperty("pmns")
public void setPmns(PmnDTO[] pmns) {
this._pmns = pmns;
}
}
Not copied here but my PmnDTO class is similar, i.e. getters and setters for each property in the pmn object of JSON.
I wrote the following code to try to map it to DTO. The library I am using is com.FasterXml.jackson (version 2.3.1)
// Got the response, construct a DTOs out of it ...
ObjectMapper mapper = new ObjectMapper();
StringReader reader = new StringReader(response); // Json Response
// Convert the JSON response to appropriate DTO ...
ModuleDTO moduleDto = mapper.readValue(reader, ModuleDTO.class);
Obviously, this code didn't work. Can someone tell, how can I map the JSON response to my DTOs, given that "modules" is an array in the JSON and it also contains a variable size array within itself.
Thank You.
(*Vipul)() ;

First of all your JSON is invalid, so I suspect you want this instead:
{
"modules": [
{
"name": "module1",
"shortId": 23425,
"pmns": [
{
"name": "pmn1",
"position": 1,
"pmnType": "D3"
},
{
"name": "pmn3",
"position": 3,
"pmnType": "R2"
},
{
"name": "pmn7",
"position": 5,
"pmnType": "S1"
}
]
},
{
"name": "module2",
"shortId": 1572,
"pmns": [
{
"name": "pmn1",
"position": 3,
"pmnType": "D3"
},
{
"name": "pmn12",
"position": 35,
"pmnType": "R2"
}
]
}
]
}
Then you can use the online conversion from JSON to POJO here and you'll get the follwing result:
-----------------------------------com.example.Example.java-----------------------------------
package com.example;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Generated;
import javax.validation.Valid;
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({
"modules"
})
public class Example {
#JsonProperty("modules")
#Valid
private List<Module> modules = new ArrayList<Module>();
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("modules")
public List<Module> getModules() {
return modules;
}
#JsonProperty("modules")
public void setModules(List<Module> modules) {
this.modules = modules;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
-----------------------------------com.example.Module.java-----------------------------------
package com.example;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Generated;
import javax.validation.Valid;
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({
"name",
"shortId",
"pmns"
})
public class Module {
#JsonProperty("name")
private String name;
#JsonProperty("shortId")
private Integer shortId;
#JsonProperty("pmns")
#Valid
private List<Pmn> pmns = new ArrayList<Pmn>();
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("name")
public String getName() {
return name;
}
#JsonProperty("name")
public void setName(String name) {
this.name = name;
}
#JsonProperty("shortId")
public Integer getShortId() {
return shortId;
}
#JsonProperty("shortId")
public void setShortId(Integer shortId) {
this.shortId = shortId;
}
#JsonProperty("pmns")
public List<Pmn> getPmns() {
return pmns;
}
#JsonProperty("pmns")
public void setPmns(List<Pmn> pmns) {
this.pmns = pmns;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
-----------------------------------com.example.Pmn.java-----------------------------------
package com.example;
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({
"name",
"position",
"pmnType"
})
public class Pmn {
#JsonProperty("name")
private String name;
#JsonProperty("position")
private Integer position;
#JsonProperty("pmnType")
private String pmnType;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("name")
public String getName() {
return name;
}
#JsonProperty("name")
public void setName(String name) {
this.name = name;
}
#JsonProperty("position")
public Integer getPosition() {
return position;
}
#JsonProperty("position")
public void setPosition(Integer position) {
this.position = position;
}
#JsonProperty("pmnType")
public String getPmnType() {
return pmnType;
}
#JsonProperty("pmnType")
public void setPmnType(String pmnType) {
this.pmnType = pmnType;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}

Related

Parsing JSON and Converting in List Of Object

I have a json response received from API Call the sample response is something like this
{
"meta": {
"code": "200"
},
"data": [
{
"Id": 44,
"Name": "Malgudi ABC"
},
{
"Id": 45,
"Name": "Malgudi, DEF"
}
]
}
I am trying to make List of Object from it, the code that i've written for this is
private static List<TPDetails> getListOfTpDetails(ResponseEntity<?> responseEntity){
ObjectMapper objectMapper = new ObjectMapper();
List<TPDetails> tpDetailsList = objectMapper.convertValue(responseEntity.getBody().getClass(), new TypeReference<TPDetails>(){});
return tpDetailsList;
}
Where TPDetails Object is Like this
public class TPDetails {
int Id;
String Name;
}
the code which i have used is resulting in
java.lang.IllegalArgumentException: Unrecognized field "meta" (class com.sbo.abc.model.TPDetails), not marked as ignorable (2 known properties: "Id", "Name"])
at [Source: UNKNOWN; line: -1, column: -1] (through reference chain: com.sbo.abc.model.TPDetails["meta"])
I want to convert the Above JSON response in List
List<TPDetails> abc = [
{"Id": 44, "Name": "Malgudi ABC"},
{"Id": 45,"Name": "Malgudi DEF"}
]
Any help would be highly appreciable.Thanks well in advance
Create 2 more classes like
public class Temp {
Meta meta;
List<TPDetails> data;
}
public class Meta {
String code;
}
and now convert this json to Temp class.
Temp temp = objectMapper.convertValue(responseEntity.getBody().getClass(), new TypeReference<Temp>(){});
UPDATED :
Make sure responseEntity.getBody() return the exact Json String which you mentioned above.
Temp temp = objectMapper.readValue(responseEntity.getBody(), new TypeReference<Temp>(){});
The format of your java class does not reflect the json you are parsing. I think it should be:
class Response {
Meta meta;
List<TPDetails> data;
}
class Meta {
String code;
}
You should then pass Response to your TypeReference: new TypeReference<Response>(){}
If you don't care about the meta field, you can add #JsonIgnoreProperties
to your response class and get rid of the Meta class and field.
Create/update following class, I am storing JSON file, since do not have service, but should be fine and Able to parse it and read it from the following model.
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import java.util.List;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"meta",
"data"
})
public class OuterPoJo {
#JsonProperty("meta")
private Meta meta;
#JsonProperty("data")
private List<TPDetails> data = null;
#JsonProperty("meta")
public Meta getMeta() {
return meta;
}
#JsonProperty("meta")
public void setMeta(Meta meta) {
this.meta = meta;
}
#JsonProperty("data")
public List<TPDetails> getData() {
return data;
}
#JsonProperty("data")
public void setData(List<TPDetails> data) {
this.data = data;
}
}
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"code"
})
public class Meta {
#JsonProperty("code")
private String code;
#JsonProperty("code")
public String getCode() {
return code;
}
#JsonProperty("code")
public void setCode(String code) {
this.code = code;
}
}
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"Id",
"Name"
})
public class TPDetails {
#JsonProperty("Id")
private Integer id;
#JsonProperty("Name")
private String name;
#JsonProperty("Id")
public Integer getId() {
return id;
}
#JsonProperty("Id")
public void setId(Integer id) {
this.id = id;
}
#JsonProperty("Name")
public String getName() {
return name;
}
#JsonProperty("Name")
public void setName(String name) {
this.name = name;
}
}
import java.io.File;
public class App {
public static void main(String[] args) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
OuterPoJo myPoJo = objectMapper.readValue(
new File("file.json"),
OuterPoJo.class);
for (TPDetails item : myPoJo.getData()) {
System.out.println(item.getId() + ":" + item.getName());
}
}
}
output:
44:Malgudi ABC
45:Malgudi, DEF

JAVA fetch data from database table with hibernate, insert this data into new table and add extra column that came in as json data with post request

So the title says what i want to do, i'm making a webapp to register customerfeedback. now what i want to do is, when a post request is invoked, i wanna fetch data from a table. then i wanna store this data into a new table with an extra column. there are several criteria that needs to be given feedback to so when the post request is invoked i need to fetch one criteria and add a selected answer to this and store it in a new table. the tables allready exist.
this is an example of how the data inside the allready existing tables look:
{
"id": "1",
"comment": "no comment",
"ratingGroups":[
{
"id": "1",
"ratingtype":"COMPANY",
"topic": "General",
"ratings":[
{
"criteria":{
"id":"1",
"name":"Contract",
"description":""
},
"scale":{
"id":"1",
"fields":[
{
"id":"1",
"label":"Bad"
},
{
"id":"2",
"label":""
},
{
"id":"3",
"label":""
},
{
"id":"4",
"label":""
},
{
"id":"5",
"label":"Good"
}
]
}
},
{
"criteria":{
"id":"2",
"name":"Timesheets",
"description":""
},
"scale":{
"id":"1",
"fields":[
{
"id":"1",
"label":"Bad"
},
{
"id":"2",
"label":""
},
{
"id":"3",
"label":""
},
{
"id":"4",
"label":""
},
{
"id":"5",
"label":"Good"
}
]
}
}]
}]
}
now i want to add a selected field in every ratings array like so(this will be in my post request):
{
"id" : "1",
"comment" : "tis gelukt!",
"ratinggroup": [{
"id": "1",
"ratings":[{
"SelectedField":{
"id":"1"
}
}]
}]
}
here is the service where i retrieve the post request
package be.i8c.customersatisfaction.msf4j;
import be.i8c.customersatisfaction.dal.DalContributionRepo;
import be.i8c.customersatisfaction.models.Contribution;
import be.i8c.customersatisfaction.models.ContributionTemplate;
import be.i8c.customersatisfaction.models.Criteria;
import be.i8c.customersatisfaction.models.Field;
import be.i8c.customersatisfaction.models.Scale;
import be.i8c.customersatisfaction.models.rating.BaseRating;
import be.i8c.customersatisfaction.models.rating.BaseRatingGroup;
import be.i8c.customersatisfaction.models.rating.RatingType;
import io.swagger.annotations.Api;
import io.swagger.annotations.Info;
import io.swagger.annotations.SwaggerDefinition;
import java.util.HashSet;
import javax.persistence.EntityManager;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Api
#SwaggerDefinition(info = #Info(title = "Customer-satisfaction", version = "v1.3"))
#Path("/customersatisfaction")
#Service
public class SatisfactionService {
#Autowired
private DalContributionRepo contributionRepository;
#GET
#Path("/{id}")
#Produces(MediaType.APPLICATION_JSON)
public Contribution get(#PathParam("id") long id) {
Contribution contribution = contributionRepository.findOne(id);
return contribution;
}
#POST
#Path("/")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public void post(Contribution contribution) {
//here i want to fetch data from a table and store it into another table with the selected field that has come through with the post request
//contributionRepository.save(contribution);
}
}
if it would only be one row in a table it probably won't be so hard but i have over 40 criteria's that should be answered, so over 40 "ratings". this makes that i will get a big json object with big arrays.
if you need more files tell me and i'l post them
You did not tell which framework are you using for persistence. From your code, I assume that it is Spring Data JPA.
I cannot give you the code in a state where you can exactly copy paste.. But i can give you the steps that you can do to achieve what you want.
To retrieve baseRating
BaseRating br = baseRatingRepo.findOne(ratingId);
To convert this to Normal Rating
NormalRating nr = new NormalRating();
nr.setProperty(br.getProperty());
nr.setSelectedField(valueOfSelectedFieldbasedOnCondition);
To save the normal Rating
normalRatingRepo.save(nr);
From your question it's really not clear what your ask is. Hope this answer helps you in someway.
Contribution.java
package be.i8c.customersatisfaction.models;
import be.i8c.customersatisfaction.models.rating.RatingGroup;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
#Entity
public class Contribution extends AbstractContribution<RatingGroup> {
#OneToOne
private ContributionTemplate template;
#ManyToOne
private Client client;
#Column
private Date date;
#Column
private String comment;
public ContributionTemplate getTemplate() {
return template;
}
public void setTemplate(ContributionTemplate template) {
this.template = template;
}
public Client getClient() {
return client;
}
public void setClient(Client client) {
this.client = client;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
}
RatingGroup.java
package be.i8c.customersatisfaction.models.rating;
import javax.persistence.Entity;
#Entity
public class RatingGroup extends AbstractRatingGroup<Rating> {
}
AbstractRatingGroup.java
package be.i8c.customersatisfaction.models.rating;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
//Superclass is not an #Entity, will NOT have its own table
#MappedSuperclass
public
abstract class AbstractRatingGroup<T extends BaseRating> {
#Id
#Column(name = "id", updatable = false, nullable = false)
private long id;
#Column
#Enumerated(EnumType.STRING)
private RatingType type;
#Column
private String topic;
#OneToMany(fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST})
private Set<T> ratings;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Set<T> getRatings() {
return ratings;
}
public void setRatings(Set<T> ratings) {
this.ratings = ratings;
}
public RatingType getType() {
return type;
}
public void setType(RatingType type) {
this.type = type;
}
public String getTopic() {
return topic;
}
public void setTopic(String topic) {
this.topic = topic;
}
}
Rating.java
package be.i8c.customersatisfaction.models.rating;
import be.i8c.customersatisfaction.models.Field;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
#Entity
public class Rating extends BaseRating {
#ManyToOne
private Field selectedField;
public Field getSelectedField() {
return selectedField;
}
public void setSelectedField(Field selectedField) {
this.selectedField = selectedField;
}
}
BaseRating.java
package be.i8c.customersatisfaction.models.rating;
import be.i8c.customersatisfaction.models.Criteria;
import be.i8c.customersatisfaction.models.Scale;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
#Entity
#Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class BaseRating {
#Id
#Column(name = "id", updatable = false, nullable = false)
private long id;
#ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.PERSIST)
private Criteria criteria;
#ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.PERSIST)
private Scale scale;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Criteria getCriteria() {
return criteria;
}
public void setCriteria(Criteria criteria) {
this.criteria = criteria;
}
public Scale getScale() {
return scale;
}
public void setScale(Scale scale) {
this.scale = scale;
}
}

Need to change my code to generate Correct JSON from Java Object - Jackson

I have following result for the query select * from student where courseName = 'Science';
Results:
student_id | name | points | course_name | course_id |
+----------+--------+--------+---------------+-----------+
1107| Matt | 3000 | Science | 10 |
| 1108| Charley| 12348 | Science | 20 |
2 rows in set, 2 warnings (0.00 sec)
StudentsDetails.java:
#Entity(name = "com.StudentDetails")
public class StudentDetails extends AbstractPersistable<Long> {
private long studentId;
private String name;
private long points;
private String courseName;
private long courseId;
public StudentDetails(long studentId, String name, long points, String courseName, long courseId) {
this.studentId = studentId;
this.name = name;
this.points = points;
this.courseName = courseName;
this.courseId = courseId;
}
public long getStudentId() {
return studentId;
}
public String getName() {
return name;
}
public long getPoints() {
return points;
}
public String getCourseName() {
return courseName;
}
public long getCourseId() {
return courseId;
}
}
I want to generate a JSON string like :
{
"items": [
{
"id": "123",
"students": [
{
"name": 'Matt',
"points": 3000,
"course_name": 'Science',
"course_id": 10
}
]
},
{
"id": "324",
"students": [
{
"name": 'Charley',
"points": 12348,
"course_name": Science,
"course_id": 20
}
]
},
{
"id": "898",
"error": {
"error_code": "500",
"error_message": "Details not found"
}
}
]
}
Part of Implementation code currently looks like :
for (int i = 0; i < studentDetails.size(); i++) {
Details details = new Details();
details.setName(studentDetails.get(i).getName());
details.setPoints(studentDetails.get(i).getPoints());
details.setCourseName(studentDetails.get(i).getCourseName());
details.setCourseId(studentDetails.get(i).getCourseId());
Listdetails.add(details);
item.setListDetails(Listdetails);
}
response = mapper.writeValueAsString(item);
Above code prints the wrong JSON like :
{"items":[{"id":"1107","details":[{"name": "Matt","points":3000,"course_name":"Science,"course_id":10},{"name":"Charley","points":12348,"course_name":"Science","course_id":20}]}]}
instead of
{"items":[{"id":"1107","details":[{"name": "Matt","points":3000,"course_name":"Science,"course_id":10}]},{"id":"1108","details":[{"name":"Charley","points":12348,"course_name":"Science","course_id":20}]}
Please help me to write a good implementation code to generate the correct JSON.
(Note : It is not the real code - just a sample of the real code)
In short : I want to read the entries from the database table and make it as:
items array -> [
0th index : student_id, other related details (1107,['Matt',3000,'Science',10]
1st index : student_id, other related details(1108,['Charley',12348,'Science',20]
]
First of all, in your Json you should use double quotes (") in order the json to be valid.
Finally you should use Jackson 2.x library. This is a cleaner way to manipulate and produce json formatted data. Below you can find a possible implementation:
-----------------------------------com.example.Error.java-------------------
package com.example;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"error_code",
"error_message"
})
public class Error {
#JsonProperty("error_code")
public String errorCode;
#JsonProperty("error_message")
public String errorMessage;
}
-----------------------------------com.example.Example.java----------------
package com.example;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"items"
})
public class Example {
#JsonProperty("items")
public List<Item> items = null;
}
-----------------------------------com.example.Item.java--------------------
package com.example;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"id",
"students",
"error"
})
public class Item {
#JsonProperty("id")
public String id;
#JsonProperty("students")
public List<Student> students = null;
#JsonProperty("error")
public Error error;
}
-----------------------------------com.example.Student.java-----------------
package com.example;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"name",
"points",
"course_name",
"course_id"
})
public class Student {
#JsonProperty("name")
public String name;
#JsonProperty("points")
public Integer points;
#JsonProperty("course_name")
public String courseName;
#JsonProperty("course_id")
public Integer courseId;
}

Create a json array

I'm writing a code where in there has to be a main array generated in json. my code is as below.
My pojos
JsonCreator.java
package com.createjson;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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)
#JsonPropertyOrder({ "EntityLabels", "ExampleText", "SelectedIntentName" })
public class Jsoncreator {
#JsonProperty("EntityLabels")
private List<EntityLabel> entityLabels = null;
#JsonProperty("ExampleText")
private String exampleText;
#JsonProperty("SelectedIntentName")
private String selectedIntentName;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("EntityLabels")
public List<EntityLabel> getEntityLabels() {
return entityLabels;
}
#JsonProperty("EntityLabels")
public void setEntityLabels(List<EntityLabel> entityLabels) {
this.entityLabels = entityLabels;
}
#JsonProperty("ExampleText")
public String getExampleText() {
return exampleText;
}
#JsonProperty("ExampleText")
public void setExampleText(String exampleText) {
this.exampleText = exampleText;
}
#JsonProperty("SelectedIntentName")
public String getSelectedIntentName() {
return selectedIntentName;
}
#JsonProperty("SelectedIntentName")
public void setSelectedIntentName(String selectedIntentName) {
this.selectedIntentName = selectedIntentName;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
EntityLabel.java
package com.createjson;
import java.util.HashMap;
import java.util.Map;
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)
#JsonPropertyOrder({ "StartToken", "EntityType", "EndToken" })
public class EntityLabel {
#JsonProperty("StartToken")
private int startToken;
#JsonProperty("EntityType")
private String entityType;
#JsonProperty("EndToken")
private int endToken;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("StartToken")
public int getStartToken() {
return startToken;
}
#JsonProperty("StartToken")
public void setStartToken(int startToken) {
this.startToken = startToken;
}
#JsonProperty("EntityType")
public String getEntityType() {
return entityType;
}
#JsonProperty("EntityType")
public void setEntityType(String entityType) {
this.entityType = entityType;
}
#JsonProperty("EndToken")
public int getEndToken() {
return endToken;
}
#JsonProperty("EndToken")
public void setEndToken(int endToken) {
this.endToken = endToken;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
Main Class
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.config.ConfigDetails;
import com.createjson.EntityLabel;
import com.createjson.Jsoncreator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class dummy {
public static void main(String[] args) throws JsonProcessingException {
Jsoncreator jsoncreator = null;
EntityLabel label;
List<EntityLabel> entityLabelList;
ObjectMapper objectMapper;
List<String> matchList;
String[] lines = { "What is (Jim)'s gift (limit)? <=> Personname <=> Amount::Spent",
"What is (John)'s gift (limit)? <=> Personname <=> Amount::Spent" };
// check if the text has entities
for (String line : lines) {
entityLabelList = new ArrayList<EntityLabel>();
if (line.contains("<=>")) {
String[] example_split = line.split("<=>", 2);
// System.out.println("String is " + example_split[1]);
if (example_split[0].length() > 1) {
String[] example_entity = example_split[1].split("<=>");
int entities_count = 0;
int startPosition;
int endPosition = 0;
matchList = new ArrayList<>();
Pattern regex = Pattern.compile("\\((.*?)\\)");
Matcher regexMatcher = regex.matcher(line);
jsoncreator = new Jsoncreator();
while (regexMatcher.find()) {
startPosition = regexMatcher.start() + 1;
endPosition = regexMatcher.end() - 1;
matchList.add(regexMatcher.group(1));
label = new EntityLabel();
label.setStartToken(startPosition);
label.setEntityType(example_entity[entities_count].toString());
label.setEndToken(endPosition);
entityLabelList.add(label);
objectMapper = new ObjectMapper();
TestCasesString = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(label);
jsoncreator.setEntityLabels(entityLabelList);
entities_count++;
}
}
}
objectMapper = new ObjectMapper();
System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsoncreator));
}
}
}
when I run this program, there are two objects created, but I want a songle object created.
My Current O/P
{
"EntityLabels" : [ {
"StartToken" : 9,
"EntityType" : " Personname ",
"EndToken" : 12
}, {
"StartToken" : 22,
"EntityType" : " Amount::Spent",
"EndToken" : 27
} ]
}
{
"EntityLabels" : [ {
"StartToken" : 9,
"EntityType" : " Personname ",
"EndToken" : 13
}, {
"StartToken" : 23,
"EntityType" : " Amount::Spent",
"EndToken" : 28
} ]
}
My Expected O/P
[{
"EntityLabels" : [ {
"StartToken" : 9,
"EntityType" : " Personname ",
"EndToken" : 12
}, {
"StartToken" : 22,
"EntityType" : " Amount::Spent",
"EndToken" : 27
} ]
},
{
"EntityLabels" : [ {
"StartToken" : 9,
"EntityType" : " Personname ",
"EndToken" : 13
}, {
"StartToken" : 23,
"EntityType" : " Amount::Spent",
"EndToken" : 28
} ]
}]
please let me know how can I do this.
Thanks
If you want an array you need to serialise a list, the same way you are already doing with entityLabels. Every jsoncreator object is going to create a json representation for that instance, just need to save them in a list and serialise it.
Something like:
public class dummy {
public static void main(String[] args) throws JsonProcessingException {
List<Jsoncreator> objectsToSerialise = new ArrayList<>();
... your code
// check if the text has entities
for (String line : lines) {
... your code
objectsToSerialise.add(jsonCreator);
}
objectMapper = new ObjectMapper();
System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(objectsToSerialise));
}
}
Hope you get the idea.
Jackson – Unmarshall to Collection/Array

printing a json array using jackson

I'm writing a program where I need to get some data from a json file and the content is as below.
{
"culture": "en-us",
"subscription_key": "myKey",
"description": "myDescription",
"name": "myName",
"appID": "myAppId",
"entities": [
{
"name": "Location"
},
{
"name": "geography"
}
]
}
using an online tool I've created the POJOs for the same. and they are as below.
ConfigDetails Pojo
package com.config;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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)
#JsonPropertyOrder({
"culture",
"subscription_key",
"description",
"name",
"appID",
"entities"
})
public class ConfigDetails {
#JsonProperty("culture")
private String culture;
#JsonProperty("subscription_key")
private String subscriptionKey;
#JsonProperty("description")
private String description;
#JsonProperty("name")
private String name;
#JsonProperty("appID")
private String appID;
#JsonProperty("entities")
private List<Entity> entities = null;
#JsonProperty("culture")
public String getCulture() {
return culture;
}
#JsonProperty("culture")
public void setCulture(String culture) {
this.culture = culture;
}
#JsonProperty("subscription_key")
public String getSubscriptionKey() {
return subscriptionKey;
}
#JsonProperty("subscription_key")
public void setSubscriptionKey(String subscriptionKey) {
this.subscriptionKey = subscriptionKey;
}
#JsonProperty("description")
public String getDescription() {
return description;
}
#JsonProperty("description")
public void setDescription(String description) {
this.description = description;
}
#JsonProperty("name")
public String getName() {
return name;
}
#JsonProperty("name")
public void setName(String name) {
this.name = name;
}
#JsonProperty("appID")
public String getAppID() {
return appID;
}
#JsonProperty("appID")
public void setAppID(String appID) {
this.appID = appID;
}
#JsonProperty("entities")
public List<Entity> getEntities() {
return entities;
}
#JsonProperty("entities")
public void setEntities(List<Entity> entities) {
this.entities = entities;
}
}
Entity POJO
package com.config;
import java.util.HashMap;
import java.util.Map;
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)
#JsonPropertyOrder({
"name"
})
public class Entity {
#JsonProperty("name")
private String name;
#JsonProperty("name")
public String getName() {
return name;
}
#JsonProperty("name")
public void setName(String name) {
this.name = name;
}
}
and I'm using the below code to print the values from the file.
MainClass obj = new MainClass();
ObjectMapper mapper = new ObjectMapper();
try {
// Convert JSON string from file to Object
ConfigDetails details = mapper.readValue(new File("properties.json"), ConfigDetails.class);
System.out.println(details.getAppID());
List entities = details.getEntities();
for (Object entity : entities) {
System.out.println(entity.toString());
}
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
The output that I'm getting is
MyAppId
com.config.Entity#2096442d
com.config.Entity#9f70c54
here instead of printing the value available, it is printing Hashcode. please let me know how can I print the values.
Thanks
Just access the getter method entity.getName() like this and use Entity instead of Object:
MainClass obj = new MainClass();
ObjectMapper mapper = new ObjectMapper();
try {
// Convert JSON string from file to Object
ConfigDetails details = mapper.readValue(new File("properties.json"), ConfigDetails.class);
System.out.println(details.getAppID());
List entities = details.getEntities();
for (Entity entity : entities) {
System.out.println(entity.getName());
}
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
You haven't defined what it means to convert an "Entity" to a String, so Java is falling back to its default way of doing this (which is to print the class name and an object ID).
What do you mean when you say you want it to "print the value available"? In this case the values are Java objects of type Entity, and you essentially are printing the values.
You can control what the String representation of an object is by overriding the toString() method. For example, you could add the following to the Entity class:
#Override
public String toString() {
return "An entity named " + name;
}

Categories

Resources