Json/Apex: Assigning values to nodes on the Json Array - json

I have an apex code that defines the JSON structure. I would like to seek for advice on how I will be able to assign values to the string fields on the JSON using Apex. The JSON will have an array (PackageData) which contains the fields that should contain the values
Apex code:
public class Shipment{
public PackageData[] PackageData;
}
public class PackageData{
public Packaging Packaging;
public Dimensions Dimensions;
public PackageWeight PackageWeight;
}
public class Packaging{
public string Code;
}
public class Dimensions{
public UnitOfMeasurement UnitOfMeasurement;
public string Length;
public string Width;
public string Height;
}
public class UnitOfMeasurement{
public string Code;
}
public class PackageWeight{
public UOM UOM;
public string Weight;
}
public class UOM{
public string Code;
}
JSON:
{
"PackageData": [
{
"Packaging": {
"Code": ""
},
"Dimensions": {
"UnitOfMeasurement": {
"Code": ""
},
"Length": "",
"Width": "",
"Height": ""
},
"PackageWeight": {
"UOM": {
"Code": ""
},
"Weight": ""
}
}
]
}

JSON are always string, so there are a parser which parse object to JSON String and vice versa
Parser does it's job and automatically parse to String, You need not worry for that
Json to Object:
ClassName objName = (ClassName) System.JSON.deserialize(jsonString, ClassName.class);
Object to Json:
String jsonString = System.JSON.serialize(objName);

Related

Parsing Complex JSON string using VB.Net

I have a complex JSON as below
{
"?xml": {
"#version": "1.0",
"#encoding": "UTF-8"
},
"env:Envelope": {
"#xmlns": "http://com/ccccc",
"#xmlns:env": "http://schemas.xmlsoap.org/soap/envelope/",
"env:Header": {
"uhtHeader": {
"#xmlns": "http://com/bbbbbb",
"consumer": "XXXXX",
"auditId": "",
"sendTimestamp": "2020-07-27T13:47:53.172-05:00",
"environment": "P",
"businessService": {
"#version": "16",
"#text": "Filename"
},
"status": "success"
}
},
"env:Body": {
"srvcRspn": {
"#xmlns": "http://com/aaaaaaa",
"srvcErrList": {
"#arrayType": "srvcErrOccur[2]",
"#type": "Array",
"srvcErrOccur": [
{
"orig": "Foundation",
"rtnCd": "00",
"explCd": "000",
"desc": ""
},
{
"orig": "YYYYYYY",
"rtnCd": "0000",
"explCd": "",
"desc": ""
}
]
},
"icn": "1234567890",
"icnSufx": "01",
"adjOfc": "123",
"fln": "12345678",
"empId": {
"id1": "S",
"ssn": "abcdefghij"
},
"engInd": "C",
"xcob": {
"ssn1": "",
"ssn9": "",
"appl": ""
},
"provList": {
"#arrayType": "provOccur[2]",
"#type": "Array",
"provOccur": [
{
"tin": "123456789012345",
"nm": "ABCD EFGH",
"typSpec": "MD"
},
{
"tin": "000000000000000",
"nm": "",
"typSpec": ""
}
]
},
"newOfc": "000",
"origOfc": "",
"drg": "",
"drgAmt": "00000000000",
"totChrg": "00000046212",
"causCd": "4",
"icdVersionInd": "",
"procCdList": {
"#arrayType": "procCdOccur[5]",
"#type": "Array",
"procCdOccur": [
{
"procCd": ""
},
{
"procCd": ""
},
{
"procCd": ""
},
{
"procCd": ""
},
{
"procCd": ""
}
]
},
"atdPhysnId": {
"drNmLst": "ABCD",
"drNmFst": "EFGH",
"drNmInit": "L"
},
"provAdr": {
"adr": "1234 ABCD EFGH",
"adr2": "",
"cty": "ABCDEFG",
"st": "AB",
"zip": "123456789"
},
"attchCdList": {
"#arrayType": "attchCd[2]",
"#type": "Array",
"attchCd": [
{
"cd": ""
},
{
"cd": ""
}
]
},
"occurCdList": {
"#arrayType": "occurCdOccur[8]",
"#type": "Array",
"occurCdOccur": [
{
"cd": "12345",
"dt": "11022020"
},
{
"cd": "1234",
"dt": "11022020"
},
{
"cd": "",
"dt": ""
},
{
"cd": "",
"dt": ""
},
{
"cd": "",
"dt": ""
},
{
"cd": "",
"dt": ""
},
{
"cd": "",
"dt": ""
},
{
"cd": "",
"dt": ""
}
]
},
"hNr": "",
"hAdmDiagCd": "",
"heDiagCd": "",
"faclRndr": {
"nm": "",
"str": "",
"cty": "",
"st": "",
"zip": ""
},
"emergInd": "",
"autoAccInd": "",
"autoAccSt": "",
"empRelInd": "",
"othrDiagList": {
"#arrayType": "othrDiagOccur[3]",
"#type": "Array",
"othrDiagOccur": [
{
"desc": ""
},
{
"desc": ""
},
{
"desc": ""
}
]
},
"nbrInsCnt": "1",
"insList": {
"#arrayType": "insOccur[1]",
"#type": "Array",
"insOccur": {
"payrNm": "ABCDEF",
"empId": "12345678",
"grpId": "",
"prrPay": "00000000000"
}
},
"typ1varList": {
"nbrLnCnt": "2",
"lnList": {
"#arrayType": "lnOccur[2]",
"#type": "Array",
"lnOccur": [
{
"plcSrvc": "AB",
"frmSrvcDt": "2020-04-21",
"toSrvcDt": "2020-04-21",
"srvcCd": "123456",
"chrgAmt": "00000024200",
"cmCd": "",
"spltLnInd": "N"
},
{
"plcSrvc": "CD",
"frmSrvcDt": "2020-04-21",
"toSrvcDt": "2020-04-21",
"srvcCd": "AA123",
"chrgAmt": "00000005877",
"cmCd": "",
"spltLnInd": "N"
}
]
}
},
"authEngTkn": "",
"adjId": ""
}
}
}
}
I need to parse this using VB.net in my application and get the values.
I have tried making the below classes using JSONUtils, but getting 4 errors
Public Class Xml
Public Property #version As String
Public Property #encoding As String
End Class
Public Class BusinessService
Public Property #version As String
Public Property #text As String
End Class
Public Class UhtHeader
Public Property #xmlns As String
Public Property consumer As String
Public Property auditId As String
Public Property sendTimestamp As DateTime
Public Property environment As String
Public Property businessService As BusinessService
Public Property status As String
End Class
Public Class EnvHeader
Public Property uhtHeader As UhtHeader
End Class
Public Class SrvcErrOccur
Public Property orig As String
Public Property rtnCd As String
Public Property explCd As String
Public Property desc As String
End Class
Public Class SrvcErrList
Public Property #arrayType As String
Public Property #type As String
Public Property srvcErrOccur As SrvcErrOccur()
End Class
Public Class EmpId
Public Property id1 As String
Public Property ssn As String
End Class
Public Class Xcob
Public Property ssn1 As String
Public Property ssn9 As String
Public Property appl As String
End Class
Public Class ProvOccur
Public Property tin As String
Public Property nm As String
Public Property typSpec As String
End Class
Public Class ProvList
Public Property #arrayType As String
Public Property #type As String
Public Property provOccur As ProvOccur()
End Class
Public Class ProcCdOccur
Public Property procCd As String
End Class
Public Class ProcCdList
Public Property #arrayType As String
Public Property #type As String
Public Property procCdOccur As ProcCdOccur()
End Class
Public Class AtdPhysnId
Public Property drNmLst As String
Public Property drNmFst As String
Public Property drNmInit As String
End Class
Public Class ProvAdr
Public Property adr As String
Public Property adr2 As String
Public Property cty As String
Public Property st As String
Public Property zip As String
End Class
Public Class AttchCd
Public Property cd As String
End Class
Public Class AttchCdList
Public Property #arrayType As String
Public Property #type As String
Public Property attchCd As AttchCd()
End Class
Public Class OccurCdOccur
Public Property cd As String
Public Property dt As String
End Class
Public Class OccurCdList
Public Property #arrayType As String
Public Property #type As String
Public Property occurCdOccur As OccurCdOccur()
End Class
Public Class FaclRndr
Public Property nm As String
Public Property str As String
Public Property cty As String
Public Property st As String
Public Property zip As String
End Class
Public Class OthrDiagOccur
Public Property desc As String
End Class
Public Class OthrDiagList
Public Property #arrayType As String
Public Property #type As String
Public Property othrDiagOccur As OthrDiagOccur()
End Class
Public Class InsOccur
Public Property payrNm As String
Public Property empId As String
Public Property grpId As String
Public Property prrPay As String
End Class
Public Class InsList
Public Property #arrayType As String
Public Property #type As String
Public Property insOccur As InsOccur
End Class
Public Class LnOccur
Public Property plcSrvc As String
Public Property frmSrvcDt As String
Public Property toSrvcDt As String
Public Property srvcCd As String
Public Property chrgAmt As String
Public Property cmCd As String
Public Property spltLnInd As String
End Class
Public Class LnList
Public Property #arrayType As String
Public Property #type As String
Public Property lnOccur As LnOccur()
End Class
Public Class Typ1varList
Public Property nbrLnCnt As String
Public Property lnList As LnList
End Class
Public Class SrvcRspn
Public Property #xmlns As String
Public Property srvcErrList As SrvcErrList
Public Property icn As String
Public Property icnSufx As String
Public Property adjOfc As String
Public Property fln As String
Public Property empId As EmpId
Public Property engInd As String
Public Property xcob As Xcob
Public Property provList As ProvList
Public Property newOfc As String
Public Property origOfc As String
Public Property drg As String
Public Property drgAmt As String
Public Property totChrg As String
Public Property causCd As String
Public Property icdVersionInd As String
Public Property procCdList As ProcCdList
Public Property atdPhysnId As AtdPhysnId
Public Property provAdr As ProvAdr
Public Property attchCdList As AttchCdList
Public Property occurCdList As OccurCdList
Public Property hNr As String
Public Property hAdmDiagCd As String
Public Property heDiagCd As String
Public Property faclRndr As FaclRndr
Public Property emergInd As String
Public Property autoAccInd As String
Public Property autoAccSt As String
Public Property empRelInd As String
Public Property othrDiagList As OthrDiagList
Public Property nbrInsCnt As String
Public Property insList As InsList
Public Property typ1varList As Typ1varList
Public Property authEngTkn As String
Public Property adjId As String
End Class
Public Class EnvBody
Public Property srvcRspn As SrvcRspn
End Class
Public Class EnvEnvelope
Public Property #xmlns As String
Public Property #xmlns:env As String
Public Property env:Header As EnvHeader
Public Property env:Body As EnvBody
End Class
Public Class Example
Public Property ?xml As Xml
Public Property env:Envelope As EnvEnvelope
End Class
The errors are listed below:
'Public Property As String' and 'Public Property As Object' cannot overload each other because they differ only by return types. generating for the lines like
Public Property #xmlns As String
'Public Property As String' has multiple definitions with identical signatures.' generating for the lines like
Public Property #version As String
'Declaration expected.' generating for the lines like
Public Property env:Header As EnvHeader
'Identifier expected.' generating for the lines like
Public Property #type As String
I am very much new in this concept and have very small idea about how to parse JSON using VB.Net.
Any help is much appreciated as I have been assigned this project suddenly with a very tight client deliverable timeline. Thanks in advance

Serialize Java List to JSON without field name

public class MyResponse {
private List<Data> data;
public static class Data {
private long id;
private String name;
}
}
Using Jackson this gets serialized to the following JSON:
{
"data": [
{
"id": 115125,
"name": "AAAY"
}
]
}
What I need instead is the JSON like this, i,e. omitting the wrapping Data class:
[
{
"id": 115125,
"name": "AAAY"
}
]
Place the #JsonValue annotation on the data field:
public class MyResponse {
#JsonValue
private List<Data> data;
...
}

How automatically parse response String into Map using RestTemplate

I'm using RestTemplate to retrieve list of issues from Jira. As response I get String with lots of fields, some of them are arrays. Request looks like:
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
Response string looks like:
{
"expand": "schema,names",
"total": 12,
"issues": [
{
"id": "32",
"key": "TEST-1",
"fields": {
"fixVersions": [
{
"description": "",
"releaseDate": "2017-04-02"
}
]
},
{
"id": "32",
"key": "TEST-2",
"fields": {
"fixVersions": [
{
"description": "",
"releaseDate": "2017-04-01"
}
]
}
]
}
Is it possible to convert this String into Map, where Object could be String or List of Map or something like this, without defining appropriate objects. As result, I'd like to have possibility to access description by: response.getIssues().get(0).getFields().getFixVersion().get(0).getDescription()
In such occasion, defining chain of specific objects looks too cumbersome.
You can create your own POJO classes which corresponds to the structure of the response JSON.
Based on the json that you have shared, you can have a class structure like this :
public class Response {
private String expand;
private String total;
private List<Issues> issues;
}
public class Issues {
private String id;
private String key;
private Map<String, List<FixVersions> fields;
}
public class FixVersions {
private String description;
private String releaseData;
}
Your GET call will change to the following :
ResponseEntity response = restTemplate.exchange(url,
HttpMethod.GET, entity, Response.class);
P.S. - All the fields in the POJO class must have their getters and
setters as well.

What is the convenient way to deserialize JSON(links + embedded container) using spring-hateoas?

colleagues!
We want to write Rest Client to service which follow the HATEOAS principle. So we have the following HAL+JSON representation and we want to deserialize it using spring-hateoas :
{
"id": "1",
"title": "album title",
"artistId": "1",
"stockLevel": 2,
"_links": {
"self": {"href": "http://localhost:8080/rest/albums/1"},
"artist": {"href": "http://localhost:8080/rest/artist/1"}
},
"_embedded": {
"albums": [{ //can be array or object
"id": "1",
"title": "album title",
"artistId": "1",
"stockLevel": 2,
"_links": {
"self": {"href": "http://localhost:8080/rest/albums/1"}
}
}],
"artist": { //can be array or object
"id": "1",
"name": "artist name",
"_links": {
"self": {"href": "http://localhost:8080/rest/artist/1"}
}
} //....
}
}
We expected the java object like this:
HalResource {
Resource<Album> //entity
List<Link> // _links
List<Resource<BaseEntity>>{ //_embedded
Resource<Album>
Resource<Artist>
....
}
}
So we have custom resource representation with embedded(list of resources) and entity(single resource):
#XmlRootElement(name = "resource")
public class HalResource<EntityType, EmbeddedType> extends Resources<EmbeddedType> {
#JsonUnwrapped
private EntityType entity;
public HalResource() {
}
public HalResource(Iterable<EmbeddedType> content, Link... links) {
super(content, links);
}
public EntityType getEntity() {
return entity;
}
public void setEntity(EntityType entity) {
this.entity = entity;
}
}
DTO classes:
public abstract class BaseEntity{}
#XmlRootElement(name = "album")
public class Album extends BaseEntity {
private String id;
private String title;
private String artistId;
private int stockLevel;
// getters and setters...
}
#XmlRootElement(name = "artist")
public class Artist extends BaseEntity {
private String id;
private String name;
// getters and setters...
}
And we want to get something like this, where Entity will be Artist or Album, but HalResourcesDeserializer return Resource.class with null content.
HalResource<Album, Resource<Entity>> resources =
restClient.getRootTarget().path("albums/1").queryParam("embedded", true).request().accept("application/hal+json")
.get(new GenericType<HalResource<Album, Resource<Entity>>>() {});
By using #JsonTypeInfo and #JsonSubTypes anotations we successfully deserialized our JSON(you can see the example on the github), but we don't want to have some additional type filds and anotattions in our DTO and JSON format.
We see one solution that is create a custom deserializer which can processing that.
So the question is: What is the convenient way to deserialize our JSON(links + embedded container) using spring-hateoas?
We use spring-hateoas 0.16v(but we tried 0.19v) and glassfish jersey 2.22.1
Thank you!

How do deserialize a json object with a Map as one of its properties

I have been using jackson to deserialize successfully json objects and arrays, but this time I just can't wrap my head around how to approach deserialization for the following object. How can I, with Jackson or any other json parsing library, deserialize:
[
{
"name": "x",
"elements": {
"key1": {
"name": "a",
"type": "b"
},
"key2": {
"name": "a",
"type": "b"
}
}
},
{
"name": "y",
"elements": {
"key3": {
"name": "a",
"type": "b"
}
}
}
]
into a list, List<Test>, where Test is defined below?
public class Test {
public class Element {
public String name;
public String type;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
public String name;
public Map<String, Element> elements;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Map<String, Element> getElements() {
return elements;
}
public void setElements(Map<String, Element> elements) {
this.elements = elements;
}
}
Finally, my deserializing code:
public List<Test> test(final InputStream inputStream) {
List<Test> test = null;
try {
test = mapper.readValue(inputStream, new TypeReference<List<Test>>() { });
} catch (final IOException e) {
log.error("Unable to deserialize json",e);
}
return test;
}
If that is not possible, what object can I actually deserialize my json into? One thing I cannot know ahead of time is the name of the keys (key1, key2, key3 in the example).
It looks like this:
ObjectMapper mapper = new ObjectMapper();
List<Test> tests = mapper.readValue(jsonInput, new TypeReference<List<Test>>() { };
would do it. The only tricky part is that TypeReference, which is needed to pass generic type information. Other libs use similar approaches (GSON has TypeToken or such).