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
Related
I am storing a custom java object called Device into a mongo collection. This works fine. But when I am receiving the database entry all inner class objects are assigned with null and not with the database value.
This is a device:
public class Device {
public String id;
public String serialNumber;
public String name;
public int status;
public String errorReport;
public List<Sensor> sensors=new ArrayList<>();
public List<Action> actions=new ArrayList<>();
public List<String> filterTags= new ArrayList<>();
public List protocols;
}
This is an example entry from the database, as you can see the values are saved well:
{
"_id": "7_openHabsamsungtv:tv:cbaf7d7d_4e10_41e6_9c1d_864988057bda",
"actions": [
{
"_id": "samsungtv:tv:cbaf7d7d_4e10_41e6_9c1d_864988057bda:volume",
"deviceId": "7_openHabsamsungtv:tv:cbaf7d7d_4e10_41e6_9c1d_864988057bda",
"errorReport": "Value wurde nicht initialisiert",
"name": "Lautst�rke",
"state": 0,
"value": 0,
"valueOption": {
"maximum": 0,
"minimum": 0,
"percentage": true
},
"valueable": true
}
],
"filterTags": [],
"name": "[TV] Chine ",
"sensors": [
{
"_id": "samsungtv:tv:cbaf7d7d_4e10_41e6_9c1d_864988057bda:sourceId",
"name": "Source ID"
},
{
"_id": "samsungtv:tv:cbaf7d7d_4e10_41e6_9c1d_864988057bda:programTitle",
"name": "Titel"
},
{
"_id": "samsungtv:tv:cbaf7d7d_4e10_41e6_9c1d_864988057bda:channelName",
"name": "Kanal"
}
],
"status": 0
}
And this is what it looks like when I am receiving it from the database again:
{
"id": "7_openHabsamsungtv:tv:cbaf7d7d_4e10_41e6_9c1d_864988057bda",
"serialNumber": null,
"name": "[TV] Chine ",
"status": 0,
"errorReport": null,
"sensors": [
{
"id": null,
"name": null,
"errorReport": null
},
{
"id": null,
"name": null,
"errorReport": null
},
{
"id": null,
"name": null,
"errorReport": null
}
],
"actions": [
{
"id": null,
"name": null,
"deviceId": null,
"state": 0,
"states": null,
"valueOption": null,
"value": 0,
"errorReport": "Value wurde nicht initialisiert",
"valueable": false
}
],
"filterTags": [],
"protocols": null
}
So when I am pulling the entries from my db collection it sets the values of the Sensor and Action to null. This is my Java Code for receiving a device:
MongoClientURI connectionString = new MongoClientURI(dummy);
MongoClient mongoClient = new MongoClient(connectionString);
CodecRegistry pojoCodecRegistry = fromRegistries(MongoClient.getDefaultCodecRegistry(),
fromProviders(PojoCodecProvider.builder().automatic(true).build()));
MongoCollection<Device> devices = database.withCodecRegistry(pojoCodecRegistry).getCollection("devices", Device.class);
Device device = devices.find().first();
I am using the standard MongoDB Java Driver.
Could anyone tell me what I am missing here? Thanks in advance.
TL;DR: You need setters and getters per default config.
I wrote this Unit-Test to reproduce the error, but it does not reproduce except when I play around with the Action and Sensor classes. I am using Mongodb 3.4 and Java driver 3.6.
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.codecs.pojo.PojoCodecProvider;
import org.junit.Test;
import static org.bson.codecs.configuration.CodecRegistries.fromProviders;
import static org.bson.codecs.configuration.CodecRegistries.fromRegistries;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertNotNull;
public class MongoDeser {
#Test
public void testDeser() {
MongoClientURI connectionString = new MongoClientURI("mongodb://localhost:27017");
MongoClient mongoClient = new MongoClient(connectionString);
MongoDatabase database = mongoClient.getDatabase("sotest");
PojoCodecProvider codecProvider = PojoCodecProvider.builder()
.automatic(true)
.build();
CodecRegistry pojoCodecRegistry = fromRegistries(MongoClient.getDefaultCodecRegistry(), fromProviders(codecProvider));
MongoCollection<Device> devices = database.withCodecRegistry(pojoCodecRegistry).getCollection("device", Device.class);
Device device = devices.find().first();
assertNotNull(device.getActions());
assertThat(device.getActions().size(), is(1));
assertThat(device.getActions().get(0).getDeviceId(), is("7_openHabsamsungtv:tv:cbaf7d7d_4e10_41e6_9c1d_864988057bda"));
assertThat(device.getStatus(), is(0));
assertThat(device.getName(), is("[TV] Chine "));
}
}
Do you have missing getters and/or setters in your POJOs?
Mongodb Java driver uses reflection for mapping POJOs from BSON. It needs these Getters and Setters per default configuration. If you don't have them, it may behave erratically. In my testing, sometimes it couldn't find a codec and threw an exception, sometimes the fields were just nulled as in your case. My recommendation would be to use annotations instead and give the Java driver a convention for it.
Sensor class
import java.io.Serializable;
public class Sensor implements Serializable
{
private String id;
private String name;
private final static long serialVersionUID = 8244091126694748358L;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Action class
import java.io.Serializable;
public class Action implements Serializable
{
private String id;
private String deviceId;
private String errorReport;
private String name;
private long state;
private long value;
private ValueOption valueOption;
private boolean valueable;
private final static long serialVersionUID = 3493217442158516855L;
public String getId() {
return id;
}
public String getDeviceId() {
return deviceId;
}
public String getErrorReport() {
return errorReport;
}
public String getName() {
return name;
}
public long getState() {
return state;
}
public long getValue() {
return value;
}
public ValueOption getValueOption() {
return valueOption;
}
public boolean isValueable() {
return valueable;
}
public static long getSerialVersionUID() {
return serialVersionUID;
}
public void setId(String id) {
this.id = id;
}
public void setDeviceId(String deviceId) {
this.deviceId = deviceId;
}
public void setErrorReport(String errorReport) {
this.errorReport = errorReport;
}
public void setName(String name) {
this.name = name;
}
public void setState(long state) {
this.state = state;
}
public void setValue(long value) {
this.value = value;
}
public void setValueOption(ValueOption valueOption) {
this.valueOption = valueOption;
}
public void setValueable(boolean valueable) {
this.valueable = valueable;
}
}
CodecRegistry codecRegistry = CodecRegistries.fromRegistries(
CodecRegistries.fromProviders(new pojoCodecRegistryCodecProvider()),
CodecRegistries.fromProviders(new ActionCodecProvider()),
CodecRegistries.fromProviders(new SensorCodecProvider()));
I'm still new to Java and parsing Json. I'm trying to build a Comic Webapp with Spring. The Database is a Json File, which holds an Array of different Comics.
I wanted to convert the Json Array to Java Objects and put it into an ArrayList but I seem to make a mistake somewhere along the way. Maybe you can tell me what I'm doing wrong? While doing a JUnit Test I get the following error:
Error com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "Comic" (class de.uni_koeln.comics.data.Comic), not marked as ignorable (6 known properties: , "title", "issue", "id", "box", "publisher", "comment"])
at [Source: N/A; line: -1, column: -1] (through reference chain: de.uni_koeln.comics.data.Comic["Comic"])
Comic.class
package de.uni_koeln.comics.data;
import de.uni_koeln.comics.service.JsonImportService;
public class Comic {
private JsonImportService jservice;
public String title;
public int id;
public int issue;
public int box;
public String publisher;
public String comment;
public Comic() {
}
public Comic(String title, int issue, int box, String publisher, String comment) {
this.title = title;
this.issue = issue;
this.box = box;
this.comment = comment;
this.publisher = publisher;
}
//setter and getter
`
JsonImportService
package de.uni_koeln.comics.service;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
#Service
public class JsonImportService {
private List<Comic> comicList;
#Test
public void readComicJson() throws JsonParseException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(new File("src/main/resources/Comics.json"));
Comic comic = mapper.treeToValue(root, Comic.class);
JsonNode contactNode = root.path("Comic");
if (contactNode.isArray()) {
for (JsonNode node : contactNode) {
String title = node.path("Title").asText();
int issue = node.path("Issue #").asInt();
int box = node.path("Box #").asInt();
String publisher = node.path("Publisher").asText();
String comment = node.path("Comments").asText();
comic.setTitle(title);
comic.setIssue(issue);
comic.setBox(box);
comic.setPublisher(publisher);
comic.setComment(comment);
comicList.add(new Comic(title,box,issue,publisher,comment));
}
}
}
public List<Comic> getComicList() {
return comicList;
}
Try to use the #JsonIgnoreProperties annotation like blow.
#JsonIgnoreProperties(ignoreUnknown = true)
public class Comic {
}
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;
}
My JSON:
{
"name": "asdf",
"age": "15",
"address": {
"street": "asdf"
}
}
If street is null, with JsonSerialize.Inclusion.NON_NULL, I can get..
{
"name": "asdf",
"age": "15",
"address": {}
}
But I want to get something like this.. (when address is not null, it is a new/empty object. But street is null.)
{
"name": "asdf",
"age": "15"
}
I thought to have custom serialization feature like JsonSerialize.Inclusion.VALID_OBJECT.
Adding isValid() method in the Address class then if that returns true serialize else don't serialize.
But I don't know how to proceed further/which class to override. Is this possible or any other views on this? Please suggest.
Added classes
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
Customer customer = new Customer();
customer.setName("name");
customer.setAddress(new Address());
mapper.writeValue(new File("d:\\customer.json"), customer);
}
#JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class Customer {
private String name;
private Address address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
#JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class Address {
private String street;
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
}
Note: I am not worrying about deserialization now. i.e, loss of address object.
Thanks in advance.
Customized JSON Object using Serialization is Very Simple.
I have wrote a claas in my project i am giving u a clue that how to Implement this in Projects
Loan Application (POJO Class)
import java.io.Serializable;
import java.util.List;
import org.webservice.business.serializer.LoanApplicationSerializer;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
#JsonSerialize(using=LoanApplicationSerializer.class)
public class LoanApplication implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private double amount;
private User borrowerId;
private String businessType;
private String currency;
private int duration;
private Date lastChangeDate;
private long loanApplicationId;
private String myStory;
private String productCategory;
private String purpose;
private Date startDate;
private String status;
private String type;
private String salesRepresentative;
Now LoanApplicationSerializer class that contains the Customization using Serialization Logic................
package org.ovamba.business.serializer;
import java.io.IOException;
import org.webservice.business.dto.LoanApplication;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
public class LoanApplicationSerializer extends JsonSerializer<LoanApplication> {
#Override
public void serialize(LoanApplication prm_objObjectToSerialize, JsonGenerator prm_objJsonGenerator, SerializerProvider prm_objSerializerProvider) throws IOException, JsonProcessingException {
if (null == prm_objObjectToSerialize) {
} else {
try {
prm_objJsonGenerator.writeStartObject();
prm_objJsonGenerator.writeNumberField("applicationId", prm_objObjectToSerialize.getLoanApplicationId());
prm_objJsonGenerator.writeStringField("status", prm_objObjectToSerialize.getStatus());
prm_objJsonGenerator.writeNumberField("amount", prm_objObjectToSerialize.getAmount());
prm_objJsonGenerator.writeNumberField("startdate", prm_objObjectToSerialize.getStartDate().getTime());
prm_objJsonGenerator.writeNumberField("duration", prm_objObjectToSerialize.getDuration());
prm_objJsonGenerator.writeStringField("businesstype", prm_objObjectToSerialize.getBusinessType());
prm_objJsonGenerator.writeStringField("currency", prm_objObjectToSerialize.getCurrency());
prm_objJsonGenerator.writeStringField("productcategory", prm_objObjectToSerialize.getProductCategory());
prm_objJsonGenerator.writeStringField("purpose", prm_objObjectToSerialize.getPurpose());
prm_objJsonGenerator.writeStringField("mystory", prm_objObjectToSerialize.getMyStory());
prm_objJsonGenerator.writeStringField("salesRepresentative", prm_objObjectToSerialize.getSalesRepresentative());
} catch (Exception v_exException) {
//ExceptionController.getInstance().error("Error while Serializing the Loan Application Object", v_exException);
} finally {
prm_objJsonGenerator.writeEndObject();
}
}
}
}
Hope This may help u alot. Thanks..
You can do it by annotating your class with #JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
Example:
#JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
public myClass{
// attributes and accessors
}
You can find some useful informations at Jackson faster xml
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);
}
}