Json Request with POSTMAN - java

I have this class:
#Getter
#Setter
IntestatarioPrivacySospensiva {
private IntestatarioInput intestatario;
private List<DatiPrivacySospensiva> datiPrivacy;
private String sportelloRiferimento;
private String riferimento;
private String note;
private String accettazioneConsensoC1;
private String accettazioneConsensoC3;
}
I have to make a JSON request to map this object, I have made this but it is never seen as IntestatarioPrivacySospensiva object.
[
{
//this are intestatarioInput variable
"abi":"abi",
"cf":"cf",
"ndg":"ndg"
},
{//This are datiprivacy variable
"tipoConsenso":"tipoConsenso",
"consenso":"consenso"
},
{
"sportelloRiferimento":"sportelloRif",
"riferimento":"riferimento",
"note":"note",
"accettazioneConsensoC1":"true",
"accettazioneConsensoC3":"false"
}
]
My service have in the request ArrayList x; how i have to map it in json?
I'm using Postman to send JSON.

I believe this should work:
[{
"sportelloRiferimento":"sportelloRif",
"riferimento":"riferimento",
"note":"note",
"accettazioneConsensoC1":"true",
"accettazioneConsensoC3":"false",
"intestatario" : {
"abi":"abi",
"cf":"cf",
"ndg":"ndg"
},
"datiPrivacy" : [ {
"tipoConsenso":"tipoConsenso",
"consenso":"consenso"
} ]
},
{
"sportelloRiferimento":"sportelloRif",
"riferimento":"riferimento",
"note":"note",
"accettazioneConsensoC1":"true",
"accettazioneConsensoC3":"false",
"intestatario" : {
"abi":"abi",
"cf":"cf",
"ndg":"ndg"
},
"datiPrivacy" : [ {
"tipoConsenso":"tipoConsenso",
"consenso":"consenso"
} ]
}]
You can use Jackson 2.x to get JSON strings from your Java objects. Checkout the below example:
https://www.mkyong.com/java/jackson-2-convert-java-object-to-from-json/

Related

Pass one attribute three times in a json array in a json serializable object in java

I am trying to duplicate the following JSON Payload using a Java serializable object.
{
"startDate": "2022-09-11",
"endDate": "9999-12-31",
"columns": [
{
"attribute": "FTOS"
},
{
"attribute": "StartDate"
},
{
"attribute": "EndDate"
}
],
"ids": [
{
"id": "EAY9",
"idType": "InvestmentId"
}
]
}
Below is the POJO and code I am trying.
public class Column{
public String attribute;
}
public class Id{
public String id;
public String idType;
}
public class Root{
public String startDate;
public String endDate;
public ArrayList<Column> columns;
public ArrayList<Id> ids;
}
The issue is while setting the attribute. If you see in the payload, we have it repeated three times whereas I am trying to set that in the following manner to replicate the same but I am getting only a single attribute in my payload. Below is the code.
Column col=new Column();
List<Column> colList=new ArrayList<>();
col.setAttribute("FTOS");
col.setAttribute("StartDate");
col.setAttribute("EndDate");
colList.add(col);
But I am getting the following payload in the actual output.
{
"startDate": "2022-09-11",
"endDate": "9999-12-31",
"columns": [
{
"attribute": "EndDate"
}
],
"ids": [
{
"id": "EAY9",
"idType": "InvestmentId"
}
]
}
The attribute you see is displayed only once. How to generate it three times as in the expected payload?
As #Anon indicated in the comments: "you need 3 objects of columns you only have one –
Anon"
Create a new Column object for each attribute you need to add to the list:
List<Column> colList=new ArrayList<>();
Column col1=new Column();
col1.setAttribute("FTOS");
colList.add(col1);
Column col2=new Column();
col2.setAttribute("StartDate");
colList.add(col2);
Column col3=new Column();
col3.setAttribute("EndDate");
colList.add(col3);

Deserialization with JSON objects which fields can be of different types

I have the following json file:
{
"authors":
[{"id":"author7",
"book":[
[
{
"value":{"pages":123}}]]},
{
"id": "author3",
"book": [
[
{
"value": {
"title": "LOTR"
}
},
{
"value": {
"boolean": false
}
},
],
[
{
"value": {
"pages": 350
}
},
{
"value": {
"boolean": false
}
},
],
[
{
"value": {
"boolean": false
}
},
{
"value": {
"pages": 150
}
},
]
]
},
}
I want to be able to create an object of Author but I am having problems while mapping the Json file with the Java classes I have created.
I understand that, while mapping the json file with the java classes, Authors class should have as fields
public class Authors{
private String authorId;
private Book book;
}
Class Book should be like this
public class Book {
private List<Values> values
public Book() {
}
}
But what about class Values?
public class Values{
private int pages;
private Boolean bool;
private String title;
public Values() {
}
}
Is this the correct way to map it? Because I see that if I create an object of Values it will ask me to modify the constructor or create a new constructor for each different object that comes from Json
Thank you for reading and helping!
Easy way out would to be to define Values by type 'object' as,
public class Book {
private List<Object> values
}
This way you won't run into the issue of having properties with null values when they don't exist in the JSON. Also, the JSON would be entirely parsed into an object even if new properties are get introduced (or which may not be defined under values class, as you have done above causing those not being mapped to the object).
However, when you are using 'object', be mindful with your logic that uses this parsed object. Although, you are assured to access the properties from the object as in the JSON, you will have to conditionally check whether the nessacary property exists first in each logical context to avoid possible undefined value errors.

Splitting a nested json to smaller jsons using Gson

I want to get a part of list json from a whole nested one. I have a json that looks like following:
{
"response": 200,
"responseMsg": "Allright",
"location": [
{
"stateId": 1,
"stateName": "West Bengal",
"district": [
{
"districtId": 15,
"districtName": "abc",
"village": [
{
"villageId": 121,
"villageName": "ABC"
},
{
"villageId": 90,
"villageName": "XYZ"
}
]
},
{
"districtId": 11,
"districtName": "xyz",
"village": [
{
"villageId": 58,
"villageName": "PQR"
}
]
}
]
}
]
}
I have written the bean files as following :
Details.java:
public class Details {
private int response = 0;
private String responseMsg = null;
private List<State> states = null;
public List<State> getLocation() {
return location;
}
State.java:
public class State {
private int stateId = 0;
private String stateName=null;
private List<District> district;
public List<District> getDistrict() {
return district;
}
Now, I want only the State json differently so that I can then use use it as List to populate the spinner in android.
For parsing the json, I am using
Gson googleJson = builder.create();Details details = googleJson.fromJson(result, Details.class);
List<State> stateList = details.getLocation();
But when i again convert this to json using gson.toJson(stateList) this gives:
[
{
"district": [
{
"village": [
{
"villageName": "Mekhliganj",
"villageId": 57
}
],
"districtName": "Cooch Bihar",
"districtId": 10
}
],"stateName=West Bengal","stateId":1
}
}
But this is other way round as state name goes in end when i again convert it to json.
Also , this same json (stateList) gives null pointer exception when I again try to parse it as:
State stateObj = gson.fromJson(stateList,State.class);
What should be the correct way to do this ? i.e. get a part of json (list) from a whole using gson and parse that part ?
Got the solution for you...
You are not passing the whole response in below function
try this steps to get whole response :
1) Store the data in String or any object class you are storing.
2)
Gson gson = new Gson();
String string = gson.toJson(response);
Note : You are just parsing remaining response. You are not parsing the original response. Just recheck the response when you parse in above function by putting break point on it.
public class Details {
private int response = 0;
private String responseMsg = null;
private Location location = null;
//add getter and setter
}
public class Location{
private List<State>stateList;
//add getter and setter
}
Finally
public class State {
private int stateId = 0;
private String stateName=null;
private List<District> district;
//add getter and setter
}

How to map Json to Java object using jackson

I am using jackson to map json which I get from my post rest api to map to a java object.
the json is represent by
{
"baseName": "xyz",
"salary": [
{
"id": 1,
"info": {
"ename": "john",
"eid": 143
}
},
{
"id": 2,
"info": {
"ename": "bg",
"eid": 123
}
}
]
}
The java class are represent by
BaseInfo.java
class BaseInfo {
String baseName;
ArrayList<salary> salaries = new ArrayList<salary>();
}
Salary.java
class Salary {
int id;
EmplInfo emp;
}
EmplInfo.java
class EmplInfo{
String ename;
int eid;
}
But in the when call the api with this json I get the arraylist initialized but contains nothings. What I am doing wrong ? I get other information like baseName,etc
You can use the JsonProperty annotation to rename properties
class BaseInfo {
String baseName;
#JsonProperty("salary")
ArrayList<salary> salaries = new ArrayList<salary>();
}
class Salary {
int id;
#JsonProperty("info")
EmplInfo emp;
}
Following are the solutions:
Either add JsonProperty annotations as specified by Michael or update json keys i.e 'salary' to 'salaries' and 'info' to 'emp'

How to Parse Nested / Multiple Json Objects using Retrofit

The JSON I'm parsing looks like this:
{ "version": 1
"data": {
"1001": {
"id": 1001,
"name": "herp",
"into": [
"3111": "we"
]
},
"1032": {
"id": 1002,
"name": "derp",
"into": [
"36": "w",
"12341: "c"
],
"tags": [
"hi there"
],
"cost" {
"even": 15
}
},
"1603": {
"id": 1003,
"name": "her",
"into": [
"37": "dll",
"58": "eow",
"32145": "3a"
],
"cost" {
"highest": 325
"lowest": 100
}
},
.... Even more data
}
The Json that is within "data" goes on for a while and does not have a set endpoint. I have no control over the Json, I'm just trying to read it. Unfortunately, with my class code I'm unable to get it to work. When I make a retrofit call the information inside "data" is empty.
I've tried many iterations of implementing this, including using a deserializer and restructuring my POJO code. This is the current state of my Data class:
public class Data {
private Map<String, Item> itemData;
// Relevant Getters, Setters and Constructors //
}
For my Item Class, the main issue is that the JSON Content isn't set, it can vary at times. As you can see above the values inside "into" vary and sometimes the amount of things within item changes as well such as "tags" or "cost":
public class Item {
private int id;
private String name;
private String group;
private String description;
private Map<String, String> into;
private List<String> tags;
private Map<String, Integer> cost;
// Relevant Getters, Setters and Constructors //
When I use this code my data class is empty, I don't see any errors in the log so I can't seem to figure out why the GSON isn't working with this.
In case you wanted to see how I construct my RestClient, here it is:
RestAdapter.Builder builder = new RestAdapter.Builder()
.setEndpoint(ROOT)
.setClient(new OkClient(new OkHttpClient()))
.setLogLevel(RestAdapter.LogLevel.FULL);
RestAdapter restAdapter = builder.build();
REST_CLIENT = restAdapter.create(DataApi.class);
I know that my Rest Query works because I can get the content within "version" but everything inside data is null.
I am officially a dumb scrub and completely looked over the easiest possible fix and should have my account and developer title revoked.
This is all I should have done:
public class ItemGroup {
private String version;
private Map<String,Item> data;
//...Man i'm so dumb...
}
AS REFERENCE FOR THE FUTURE. The reason why this works is because the JSON is in this format { { } { } { } }. Which means you have 3 objects of objects, as opposed to { [ ] [ ] [ ] } which is 3 objects of a list. What I had done was treat { { } { } { } } as { { { } { } { } } }. Which is not correct. By using a map which is basically a collection of pairs, we are able to imitate the { { } { } { } } with a Map.
Map Object { {Key-Pair Object} {Key-Pair Object} {Key-Pair Object} }
Just a quick idea for your Pojos:
Not sure if this will work. Maybe write a custom deserializer.
public class YourResponse {
int version;
Data data;
class Data {
Subdata subData;
}
class Subdata {
private int id;
private String name;
private ArrayList<Into> into;
private ArrayList<String> tags;
//...
}
class Into {
// "3111": "we"
private String into;
}
}

Categories

Resources