Java Spring Deserializing Nested objects using RestTemplate - java

I am using Java Spring boot restTemplate and I am trying to deserialize the below JSON into their corresponding objects. However it is returning null.
Am I doing this the right way? Should I return a String response Entity and then convert?
{
"Events": [
{
"Id": 3584588,
"Url": "https://api.wildapricot.org/v2/accounts/257051/Events/3584588",
"EventType": "Regular",
"StartDate": "2019-10-07T07:00:00-05:00",
"EndDate": "2019-10-11T12:00:00-05:00",
"Location": "Renaissance Montgomery Hotel & Spa",
"RegistrationEnabled": false,
"RegistrationsLimit": null,
"PendingRegistrationsCount": 0,
"ConfirmedRegistrationsCount": 0,
"CheckedInAttendeesNumber": 0,
"InviteeStat": {
"NotResponded": 0,
"NotAttended": 0,
"Attended": 0,
"MaybeAttended": 0
},
"Tags": [
"event"
],
"AccessLevel": "AdminOnly",
"StartTimeSpecified": true,
"EndTimeSpecified": true,
"HasEnabledRegistrationTypes": false,
"Name": "2020 Montgomery IT Summit"
},
{
"Id": 3584591,
"Url": "https://api.wildapricot.org/v2/accounts/257051/Events/3584591",
"EventType": "Rsvp",
"StartDate": "2019-10-03T00:00:00-05:00",
"EndDate": "2019-10-31T00:00:00-05:00",
"Location": "Here",
"RegistrationEnabled": true,
"RegistrationsLimit": null,
"PendingRegistrationsCount": 0,
"ConfirmedRegistrationsCount": 0,
"CheckedInAttendeesNumber": 0,
"InviteeStat": {
"NotResponded": 0,
"NotAttended": 0,
"Attended": 0,
"MaybeAttended": 0
},
"Tags": [
"volunteer"
],
"AccessLevel": "Public",
"StartTimeSpecified": false,
"EndTimeSpecified": false,
"HasEnabledRegistrationTypes": true,
"Name": "Volunteer Event"
}
]
}
Here is my call:
ResponseEntity<WaEvents> response = restTemplate.exchange(uri,
HttpMethod.GET,
request,
WaEvents.class
);
return response.getBody().getEvents();
Here is my WaEvents Class:
#Data
public class WaEvents implements Serializable {
#JsonUnwrapped
#JsonProperty("Events")
private List<WaEvent> events;
}
Here is the WaEvent Class
#Data
#JsonIgnoreProperties(ignoreUnknown = true)
public class WaEvent {
#JsonProperty("Id")
public Integer id;
#JsonProperty("Name")
public String name;
#JsonProperty("Location")
public String location;
#JsonProperty("StartDate")
public LocalDate startDate;
#JsonProperty("EndDate")
public LocalDate endDate;
#JsonProperty("IsEnabled")
public Boolean isEnabled;
#JsonProperty("Description")
public String description;
#JsonProperty("RegistrationLimit")
public Integer RegistrationLimit;
}

As explained here with an example :
public class Parent {
public int age;
public Name name;
}
public class Name {
public String first, last;
}
Without #JsonUnwrapped, the JSON is :
{
"age" : 18,
"name" : {
"first" : "Joey",
"last" : "Sixpack"
}
}
With #JsonUnwrapped, the JSON is :
{
"age" : 18,
"first" : "Joey",
"last" : "Sixpack"
}
So #JsonUnwrapped will flatten the properties and events won't exist anymore :
{
"Id": 3584588,
"Name": "2020 Montgomery IT Summit",
"Location": "Renaissance Montgomery Hotel & Spa",
"StartDate": "2019-10-07T07:00:00-05:00",
"EndDate": "2019-10-11T12:00:00-05:00",
...
}
Try to remove #JsonUnwrapped

Related

How to add link to parent object in schema

I have a simple dto
#Getter
#Setter
#Schema(title = "TestDto", description = "Test dto")
public class TestDto {
private Integer id;
private String value;
#ArraySchema(schema = #Schema(implementation = TestDto.class))
private List<TestDto> children;
and when i generate schema i see
"testDto": [
{
"id": 0,
"value": "string",
"children":["string"]
}
but i need something like this
"testDto": [
{
"id": 0,
"value": "string",
"children":[
{"id": 0,
"value": "string",
"children":[{}]}]
}
or like this
"testDto": [
{
"id": 0,
"value": "string",
"children":["testDto"]
}
is there any way to do that?

Spring Data Mongodb Aggregation - Group by nested objects and build DTO

I have the following Employee data in MongoDB
{
"_id": {
"$oid": "625f09bb1a96bf42ff4c4006"
},
"employeeId": 1234,
"email": "jason#acme.com",
"firstName": "Jason",
"lastName": "Stuart",
"currentCTC": 1201117.61,
"department": {
"$ref": "department",
"$id": {
"$oid": "625f09bb1a96bf42ff4c4005"
}
}
}
{
"_id": {
"$oid": "625f09bb1a96bf42ff4c4006"
},
"employeeId": 1235,
"email": "jasons#acme.com",
"firstName": "Jasons",
"lastName": "Stuarts",
"currentCTC": 1201117.61,
"department": {
"$ref": "department",
"$id": {
"$oid": "625f09bb1a96bf42ff4c4005"
}
}
}
My Spring #Document looks like this:
// Employee.java
#Data
#Document
public class Employee {
#Id
private String id;
private Long employeeId;
private String email;
private String firstName;
private String middleName;
private String lastName;
private Gender gender;
private double currentCTC;
#DBRef
private Department department;
}
// Department.java
#Document
#Data
public class Department {
#Id
private String id;
private String name;
}
Now, my requirement is to find the sum of salaries Department-wise.. I need the data to be in the following way:
[
{
"department": {
"id": "625f09bb1a96bf42ff4c4006",
"name": "Engineering"
},
"cost": 31894773.01
},
{
"department": {
"id": "625f09bb1a96bf42ff4c4006",
"name": "Marketing"
},
"cost": 4552325.25
}
]
I created an aggregate function like this in Spring Data:
public List<DepartmentCost> getDepartmentCosting() {
GroupOperation groupByDepartment = group("department").sum("currentCTC").as("cost").first("$$ROOT").as("department");
Aggregation aggregation = Aggregation.newAggregation(groupByDepartment);
AggregationResults<DepartmentCost> results = mongoTemplate.aggregate(aggregation, "employee", DepartmentCost.class);
return results.getMappedResults();
}
And my expected DepartmentCost.java
#Data
#Document
public class DepartmentCost {
#DBRef
private Department department;
private double cost;
}
Now when I try this API out, I get the data correctly, but I do not get department name. It comes as null. I get a response like
[
{
"department": {
"id": "625f09bb1a96bf42ff4c4006",
"name": null,
},
"cost": 2241117.6100000003
},
{
"department": {
"id": "625f09bb1a96bf42ff4c400a",
"name": null,
},
"cost": 14774021.43
},
{
"department": {
"id": "625f09bc1a96bf42ff4c4013",
"name": null,
},
"cost": 14879633.97
}
]
How can I get the department details expanded in my model? Please help..
After a couple of attempts, I figured it out. All I had to do was this:
GroupOperation groupByDepartment = group("department").sum("currentCTC").as("cost").first("$department").as("department");
as opposed to:
GroupOperation groupByDepartment = group("department").sum("currentCTC").as("cost").first("$$ROOT").as("department");

I'm trying to deserialize a Json using ObjectMapper but it fails to deserialize date value

Solve it by replacing all Date types to String
It's a JSON from marvel comics API I'm trying to deserialize and I'm getting
"com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance
of `com.example.demo.json2csharp.Date` (although at least one Creator exists):
no String-argument constructor/factory method to deserialize from String value
('2019-11-07T08:46:15-0500')"
, example of JSON:
{
"code": 200,
"status": "Ok",
"copyright": "© 2021 MARVEL",
"attributionText": "Data provided by Marvel. © 2021 MARVEL",
"attributionHTML": "Data provided by Marvel. © 2021 MARVEL",
"etag": "f712574873e89d0505dc68a908170fb7970d2f13",
"data": {
"offset": 0,
"limit": 20,
"total": 1,
"count": 1,
"results": [
{
"id": 82967,
"digitalId": 0,
"title": "Marvel Previews (2017)",
"issueNumber": 0,
"variantDescription": "",
"description": null,
"modified": "2019-11-07T08:46:15-0500",
"isbn": "",
"upc": "75960608839302811",
"diamondCode": "",
"ean": "",
"issn": "",
"format": "",
"pageCount": 112,
"textObjects": [
],
"resourceURI": "http://gateway.marvel.com/v1/public/comics/82967",
"urls": [
{
"type": "detail",
"url": "http://marvel.com/comics/issue/82967/marvel_previews_2017?utm_campaign=apiRef&utm_source=9a0517af422c1dfbe132dbaf086fa7f7"
}
],
"series": {
"resourceURI": "http://gateway.marvel.com/v1/public/series/23665",
"name": "Marvel Previews (2017 - Present)"
},
"variants": [
{
"resourceURI": "http://gateway.marvel.com/v1/public/comics/82965",
"name": "Marvel Previews (2017)"
},
{
"resourceURI": "http://gateway.marvel.com/v1/public/comics/82970",
"name": "Marvel Previews (2017)"
}
],
"collections": [
],
"collectedIssues": [
],
"dates": [
{
"type": "onsaleDate",
"date": "2099-10-30T00:00:00-0500"
},
{
"type": "focDate",
"date": "2019-10-07T00:00:00-0400"
}
],
"prices": [
{
"type": "printPrice",
"price": 0
}
],
"thumbnail": {
"path": "http://i.annihil.us/u/prod/marvel/i/mg/b/40/image_not_available",
"extension": "jpg"
},
"images": [
],
"creators": {
"available": 1,
"collectionURI": "http://gateway.marvel.com/v1/public/comics/82967/creators",
"items": [
{
"resourceURI": "http://gateway.marvel.com/v1/public/creators/10021",
"name": "Jim Nausedas",
"role": "editor"
}
],
"returned": 1
},
"characters": {
"available": 0,
"collectionURI": "http://gateway.marvel.com/v1/public/comics/82967/characters",
"items": [
],
"returned": 0
},
"stories": {
"available": 2,
"collectionURI": "http://gateway.marvel.com/v1/public/comics/82967/stories",
"items": [
{
"resourceURI": "http://gateway.marvel.com/v1/public/stories/183698",
"name": "cover from Marvel Previews (2017)",
"type": "cover"
},
{
"resourceURI": "http://gateway.marvel.com/v1/public/stories/183699",
"name": "story from Marvel Previews (2017)",
"type": "interiorStory"
}
],
"returned": 2
},
"events": {
"available": 0,
"collectionURI": "http://gateway.marvel.com/v1/public/comics/82967/events",
"items": [
],
"returned": 0
}
}
]
}
}
My Date class, like all the others class used in ObjectMapper, was generated at https://json2csharp.com/json-to-pojo:
public class Date {
#JsonProperty("type")
public String getType() {
return this.type;
}
public void setType(String type) {
this.type = type;
}
String type;
#JsonProperty("date")
public Date getDate() {
return this.date;
}
public void setDate(Date date) {
this.date = date;
}
Date date;
public Date() {
}
}
The method calling the mapper is this:
#PostMapping
public Root getComic(#RequestBody ComicPostRequestBody comicPostRequestBody) throws NoSuchAlgorithmException, URISyntaxException, IOException {
URI uri = comicService.makeUrl(comicPostRequestBody.getComicId());
String json = client.getComic(uri);
ObjectMapper mapper = new ObjectMapper();
Root comicWrapper = mapper.readValue(json, Root.class);
return comicWrapper;
}
Root is the Class that contains all properties
public class Root {
int code;
String status;
String copyright;
String attributionText;
String attributionHTML;
String etag;
Data data;
#JsonProperty("code")
public int getCode() {
return this.code;
}
public void setCode(int code) {
this.code = code;
}
#JsonProperty("status")
public String getStatus() {
return this.status;
}
public void setStatus(String status) {
this.status = status;
}
#JsonProperty("copyright")
public String getCopyright() {
return this.copyright;
}
public void setCopyright(String copyright) {
this.copyright = copyright;
}
#JsonProperty("attributionText")
public String getAttributionText() {
return this.attributionText;
}
public void setAttributionText(String attributionText) {
this.attributionText = attributionText;
}
#JsonProperty("attributionHTML")
public String getAttributionHTML() {
return this.attributionHTML;
}
public void setAttributionHTML(String attributionHTML) {
this.attributionHTML = attributionHTML;
}
#JsonProperty("etag")
public String getEtag() {
return this.etag;
}
public void setEtag(String etag) {
this.etag = etag;
}
#JsonProperty("data")
public Data getData() {
return this.data;
}
public void setData(Data data) {
this.data = data;
}
public Root() {
}
}
My final goal is to create a comic with:
results.id
results.title
results.description
results.isbn
results.price
I'm new to programming at all and the way I found to do it was to deserialize all the json into a Root, so I can get all these properties like root.getData().getResults()
If there's a simple way to solve this or to deserialize this JSON I'll be glad to know
Thanks

Deserialize complex JSON to Java, classes nested multiple levels deep

I am trying to make the Json output from Cucumber into a single Java object. This contains objects nested four levels deep, and I am having trouble deserializing it. I am presently using Jackson, but open to suggestions.
Here is my Json code:
{
"line": 1,
"elements": [
{
"line": 3,
"name": "Converteren centimeters naar voeten/inches",
"description": "",
"id": "applicatie-neemt-maten-in-cm-en-converteert-ze-naar-voet/inch,-en-vice-versa;converteren-centimeters-naar-voeten/inches",
"type": "scenario",
"keyword": "Scenario",
"steps": [
{
"result": {
"duration": 476796588,
"status": "passed"
},
"line": 4,
"name": "maak Maten-object aan met invoer in \"centimeters\"",
"match": {
"arguments": [
{
"val": "centimeters",
"offset": 37
}
],
"location": "StepDefinition.maakMatenObjectAanMetInvoerIn(String)"
},
"keyword": "Given "
},
{
"result": {
"duration": 36319,
"status": "passed"
},
"line": 5,
"name": "ik converteer",
"match": {
"location": "StepDefinition.converteerMaten()"
},
"keyword": "When "
},
{
"result": {
"duration": 49138,
"status": "passed"
},
"line": 6,
"name": "uitvoer bevat maat in \"voeten/inches\"",
"match": {
"arguments": [
{
"val": "voeten/inches",
"offset": 23
}
],
"location": "StepDefinition.uitvoerBevatMaatIn(String)"
},
"keyword": "Then "
}
]
},
{
"line": 8,
"name": "Converteren voeten/inches naar centimeters",
"description": "",
"id": "applicatie-neemt-maten-in-cm-en-converteert-ze-naar-voet/inch,-en-vice-versa;converteren-voeten/inches-naar-centimeters",
"type": "scenario",
"keyword": "Scenario",
"steps": [
{
"result": {
"duration": 84175,
"status": "passed"
},
"line": 9,
"name": "maak Maten-object aan met invoer in \"voeten/inches\"",
"match": {
"arguments": [
{
"val": "voeten/inches",
"offset": 37
}
],
"location": "StepDefinition.maakMatenObjectAanMetInvoerIn(String)"
},
"keyword": "Given "
},
{
"result": {
"duration": 23928,
"status": "passed"
},
"line": 10,
"name": "ik converteer",
"match": {
"location": "StepDefinition.converteerMaten()"
},
"keyword": "When "
},
{
"result": {
"duration": 55547,
"status": "passed"
},
"line": 11,
"name": "uitvoer bevat maat in \"centimeters\"",
"match": {
"arguments": [
{
"val": "centimeters",
"offset": 23
}
],
"location": "StepDefinition.uitvoerBevatMaatIn(String)"
},
"keyword": "Then "
}
]
}
],
"name": "Applicatie neemt maten in cm en converteert ze naar voet/inch, en vice versa",
"description": "",
"id": "applicatie-neemt-maten-in-cm-en-converteert-ze-naar-voet/inch,-en-vice-versa",
"keyword": "Feature",
"uri": "sample.feature"
}
I have tried a number of different approaches. First I used nested inner classes, but it appeared you had to make them static, which I feared would not work since I have multiple instances of the same object within one (multiple "element"-objects in the root, for example). Then I tried putting them in separate classes, with Json annotations. Here's where that got me (omitting setters):
public class CucumberUitvoer {
private String name;
private String description;
private String id;
private String keyword;
private String uri;
private int line;
#JsonProperty("elements")
private List<FeatureObject> elements;
public CucumberUitvoer(){}
}
public class FeatureObject {
private String name;
private String description;
private String id;
private String type;
private String keyword;
private int line;
#JsonProperty("steps")
private List<StepObject> steps;
public FeatureObject() {
}
}
public class StepObject {
#JsonProperty("result")
private ResultObject result;
private String name;
private String given;
private String location;
private String keyword;
private int line;
#JsonProperty("match")
private MatchObject match;
public StepObject(){}
}
public class ResultObject {
private int duration;
private String status;
public ResultObject(){}
}
public class MatchObject {
#JsonProperty("arguments")
private List<ArgumentObject> arguments;
private String location;
public MatchObject(){}
}
public class ArgumentObject {
private String val;
private String offset;
public ArgumentObject(){}
}
For clarification, here's a class diagram of how the nesting works.
This solution gives me the following error:
com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of nl.icaprojecten.TestIntegratieQuintor.JSONInterpreter.CucumberUitvoer out of START_ARRAY token
Here is the code doing the actual mapping:
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
CucumberUitvoer obj1 = null;
try {
obj1 = mapper.readValue(json, CucumberUitvoer.class);
} catch (IOException e) {
e.printStackTrace();
}
Is there a quick fix to this approach to make it work, or should I try something entirely different?
Ok I spent some time debugging and trying to figure out what was the problem, and finally was something pretty obvious.
implements Serializable
Thats the line I added to MatchObject and worked.
When we try to deserialize some object first we have to make those classes implements the interface Serializable
I just tried your sample code and oddly, it works.
Can you please double check your imports, if the JSON is coming in as provided and the getters, setters, constructors are actually there?
You can get the idea from this code to deserialize,
public class testCustomDeSerializer extends JsonDeserializer<test> {
public testCustomDeSerializer() {
this(null);
}
public TestCustomDeSerializer(Class t) {
// super(t);
}
#Override
public Test deserialize(JsonParser p, DeserializationContext ctx) throws IOException, JsonProcessingException {
ObjectCodec objectCodec = p.getCodec();
JsonNode node = objectCodec.readTree(p);
ObjectMapper objectMapper = new ObjectMapper();
Test test= new Test();
test.setId(node.get("line").asText());
List<elements> elementList = new ArrayList<>();
JsonNode elementsNode = node.get("elements");
Iterator<JsonNode> slaidsIterator = elementsNode.elements();
while (slaidsIterator.hasNext()) {
Steps steps= new Steps();
JsonNode slaidNode = slaidsIterator.next();
JsonNode stepNode= (JsonNode) slaidNode.get("Steps");
BoundingPoly in = objectMapper.readValue(stepNode.toString(), Steps.class);
elementsNode.setSteps(in);
/// continue
return
}
Hope it helps

Mapping JSONArray in RestTemplate Spring

I am trying to map this JSONArray using Spring RestTemplate:
[{
"Command": "/usr/sbin/sshd -D",
"Created": 1454501297,
"Id": "e00ca61f134090da461a3f39d47fc0cbeda77fbbc0610439d3c16a932686b612",
"Image": "ubuntu:latest",
"Labels": {
},
"Names": [
"/nova-c1896fbd-1309-4da2-8d77-b4fe4c02fa8e"
],
"Ports": [
],
"Status": "Up 2 hours"
}, {
"Command": "/usr/sbin/sshd -D",
"Created": 1450106126,
"Id": "7ffc9dbdd200e2c23adec442abd656ed57306955332697cb7da979f36ebf3b22",
"Image": "ubuntu:latest",
"Labels": {
},
"Names": [
"/nova-93b9ae40-8135-48b7-ac17-12094603b28c"
],
"Ports": [
],
"Status": "Up 2 hours"
}]
Here is ContainersInfo class:
#JsonIgnoreProperties(ignoreUnknown = true)
public class ContainersInfo {
private String Id;
private List<String> Names;
public String getId() {
return Id;
}
public void setId(String id) {
Id = id;
}
public List<String> getNames() {
return Names;
}
public void setNames(List<String> names) {
Names = names;
}
}
However I get null when I want to get the data:
ContainersInfo[] containers = syncRestTemplate.getForObject("http://192.168.1.2:4243/containers/json?all=1", ContainersInfo[].class);
for (int i = 0; i < containers.length; i++)
System.out.println("id:" + containers[i].getId());
The resulting output is as follows:
id:null
id:null
Any idea, what I should do?
Your JSON field names are in pascal case as opposed to camel case (which is usually the case). Set Jackson naming strategy to PascalCaseStrategy, i.e by adding #JsonNaming(PascalCaseStrategy.class) annotation into ContainersInfo class.

Categories