How to send multiple json objects in a post request using retrofit? - java

I have this json object of key value pairs that needs to be sent in a post request using retrofit
{
"Criteria":{
"DisciplineId":0,
"SeasonId":0,
"Leagues":[
],
"StartDate":"06 Sep 2013",
"EndDate":"14 Dec 2013",
"RoundId":0,
"GroupId":0,
"MatchesScores":3
},
"SearchInfo":{
"PageNumber":1,
"PageSize":20,
"Sort":1,
"TotalRecords":542
}
}
I was thinking of creating a POJO that matches the gson definition of the json object then using the setters in the POJO class to set the value for each key value pair.
So I would have something like this
#FormUrlEncoded
#POST("/getMatches")
void getMatches(#Field("Criteria") Criteria criteria,#Field("SearchInfo") SearchInfo searchInfo, Callback<JSONKeys> keys);
Am I on the right track?
How can I achieve this seeing that there are two nested json objects within the json object as well as a json array with one of these objects?

You could create a request class that contains both of those. As long as the names of the member variables match the json (or you use SerializedName) the conversion happens automatically.
class MyRequest{
#SerializedName("Criteria") Criteria criteria;
#SerializedName("SearchInfo") SearchInfo searchInfo;
}
Where Criteria is:
class Criteria {
#SerializedName("DisciplineId") int disciplineId;
#SerializedName("SeasonId") int seasonId;
#SerializedName("Leagues") List<Integer> leagues; // Change Integer to datatype
#SerializedName("StartDate") String startDate;
#SerializedName("EndDate") String endDate;
#SerializedName("RoundId") int roundId;
#SerializedName("GroupId") int groupId;
#SerializedName("MatchesScores") int matchesScores;
}
And SearchInfo is:
class SearchInfo{
#SerializedName("PageNumber") int pageNumber;
#SerializedName("PageSize") int pageSize;
#SerializedName("Sort") int sort;
#SerializedName("TotalRecords") int totalRecords;
}
To use try (see here):
#POST("/getMatches")
public void getMatches(#Body MyRequest request, Callback<Boolean> success);
Retrofit uses Gson internally and will automatically convert your MyRequest Object to the json format you've described in your question.
Note: Usually it's convention to name the json keys as lowercase-with-underscore, and java with camelcase. Then instead of using SerializedName everywhere, you set your key naming convention when creating your gson object (see here):
Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.create()

Related

Changing POJO structure on returning to API call

I have assigned values to my POJO class to return as response body to an API call. I want to change my POJO structure, like by making the POJO as value to an object on top of the POJO.
For example:
Home POJO:
{
int number;
String address;
}
Values are assigned to the POJO and I can send it as response body to my API call, but I want my response body to be:
{
output: {
number: 1,
address: "chennai"
}
}
I know that I can achieve this using JSON-Object or using a HashMap or a parent POJO (Note: I do not want to create a POJO Output just for this case).
Is there any other way to serialize the POJO like this using Jackson or any other methods for Java with Spring?
You can apply #JsonRootName annotation on your class specifying "output" as its value.
#JsonRootName("output")
public class MyPojo {
private int number;
private String address;
// all-args constructor, getters, etc.
}
But this annotation alone would not have any impact on serialization. In order to make to instruct Jackson to use it, we need to enable the serialization feature WRAP_ROOT_VALUE:
Feature that can be enabled to make root value (usually JSON Object but can be any type) wrapped within a single property JSON object, where key as the "root name", ...
Usage example:
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
System.out.println(
mapper
.writerWithDefaultPrettyPrinter()
.writeValueAsString(new MyPojo(1000, "foo"))
);
Output:
{
"output" : {
"number" : 1000,
"address" : "foo"
}
}

How to save google JsonObject field into dynamoDB?

I have json request like below.
{
"color":"red",
"type":"publish",
"events":{
"some":"Yes",
"collection":[
{
"key1":"value1",
"key2":"value2"
},
{
"key3":"value3",
"key4":"value4"
}
],
"nestedObject":{
"key5":"value5",
"key6":"value6"
}
}
}
I have create POJO class with color as String, type as string, and events as JsonObject. Value of events field can be any value of json format. So I created it as JsonObject. My question is how can I store events into the data base. For dynamo we can use #DynamoDBDocument annotation to marshal other object into current POJO. Now I cant use because we have to annotate to the class to marshall. In this case JsonObject is out of my scope to annotate. Is there any other way to store JsonObject into dynamo?
You will need to use the WithJSON Method to save the string representation
String jsonDoc = json.toString();
Item item = new Item()
.withPrimaryKey("pid", "Test")
.withJSON("doc", jsonDoc);
table.putItem(item);
You can also refer to the following AWS documentation:
http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/JavaDocumentAPIItemCRUD.html#PutDocumentAPIJava

Parse JSON without object name in Java

I am trying to parse this JSON which is coming as the response to a REST API call. Can you please help me parsing it as key value pairs?
The object names are not present. There is nesting as well. There seems to be no new line between records.
The aim is to extract this data and load it into a database.
[
{
"cc_emails":["feedback#xyz.com"],
"fwd_emails":[],
"reply_cc_emails":["feedback#xyz.com"],
"fr_escalated":false,
"spam":false,
"email_config_id":6000038087,
"group_id":6000110481,
"priority":1,
"requester_id":6010410791,
"responder_id":6002817857,
"source":1,
"company_id":null,
"status":2,
"subject":"fare",
"to_emails":["feedback#xyz.com"],
"product_id":null,
"id":45043,
"type":null,
"due_by":"2016-03-12T08:58:02Z",
"fr_due_by":"2016-03-08T08:58:02Z",
"is_escalated":false,
"description":"Dear xyze Team,\r\n\r\nWhy r u increased fair again and againasas0mail.gmail.com</a>.<br>\n",
"custom_fields":
{
"category":null,
"issue":null,
"route_id":null,
"phone_number":null,
"department":null,
"booking_id":null
},
"created_at":"2016-03-07T08:58:02Z",
"updated_at":"2016-03-07T08:58:03Z",
// ...... repeat
}
]
The best way to do this would be to use http://www.jsonschema2pojo.org/
Enter your json there
Change source type to JSON
set the correct class name and package.
The resulting pojo can be directly mapped from the json
If you are using resttemplate to hit the api then you can use getForObject to automatically set the pojo from the output.
https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html#getForObject-java.lang.String-java.lang.Class-java.lang.Object...-
Using gson you can do this quite simply.
Do a class to match the fields in the json something like:
public class Example {
private List<String> cc_emails;
private List<String> fwd_emails;
private List<String> reply_cc_emails;
private Boolean fr_escalated;
private Boolean spam;
private Integer email_config_id;
...
private CustomFields custom_fields;
private String created_at;
private String updated_at;
}
Then you need to do another to map the custom fields
public class CustomFields {
private String category;
...
}
And using json you can parse it like this:
Type type = new TypeToken<Collection<Example>>(){}.getType();
new Gson().fromJson(json,type);
You have to exaplain to Gson it's a list, if it was a single object it would be this:
new Gson().fromJson(json,Example.class);
This is the aproach I usually take, also in the dates java.sql.Timestamp class might also parse it, you would need to try it though.
You can use Gson (https://github.com/google/gson) or Jackson (https://github.com/FasterXML/jackson) and deserialize it to a Map.

How to combine/separate multiple json

i have a json which contains 2 json Objects
{"cityList":[{"id":"2","cityName":"value"}]}
{"subGuildList":[{"id":"340","guildId":"144","subGuildName":"value"}]}
now i want to combine 2 jsons object to one.
What is the integration of the two json object above?
and how can i to separate main json object with java or android?
use Gson or some similar json converter. your Json in incorrect. if you say 1 json contains those 2 object then it's rep should be:
{
"cityList":[{"id":"2","cityName":"value"}],
"subGuildList":[{"id":"340","guildId":"144","subGuildName":"value"}]
}
Your POJO will be:
public class MyObject {
private List<MyCity> cityList;
private List<MyGuid> subGuidList;
}
public class MyCity {
int id;
String cityName;
}

"Dotting" in JSON using Gson on Android

I'm trying to parse a JSON feed using Gson in Android. I know the JSON is valid. I suspect that it is because the format is like this:
"Info":[
{
"Id":"",
"Name":"",
"Description":"",
"Date":""
}
In order to parse this I need to "dot" in. Ex: Info.Name
How can I do this in a serialized DTO?
#SerializedName("Name")
public String name;
#SerializedName("Description")
public String desc;
#SerializedName("Date")
public String date;
I tried to put "Info." in front of each serializedName but that didn't work either. I also know my JSON parsing method works properly, because it's used somewhere else with a different DTO. But in that parsing, I don't have to "dotting" issue.
Can anyone help?
EDIT: I have tried everything you guys posted, and nothing works. The error says:
The JsonDeserializer failed to deserialize json object {"Info":[{".......
SECOND EDIT:
I was able to get rid of the error, but now it returns null. Haha, getting pretty damn frustrated right about now!
I am assuming that the actual JSON you are intaking is valid because the example you provided is not. In your JSON example, you have "Info":[ but there is no outer object containing the "Info" property, which is a must. The valid JSON would be:
{
"Info": [
{
"Id":"",
"Name":"",
"Description":"",
"Date":"",
}
]
}
This is a JSON object that has a property "Info" which has a value that is a list of objects. This list of objects contains one object that has the properties "Id", "Name", "Description", and "Date", all of which have empty-string values.
Here is a quick tutorial on how to use GSON to parse a JSON feed such as the above JSON:
You will need a class to represent the items in the list:
public class InfoItem {
public String Id;
public String Name;
public String Description;
public String Date;
public InfoItem() {}
}
And one to represent the list of Items:
public class InfoItemList extends LinkedList<InfoItem> {
public InfoItemList() { super() };
}
This added complexity is because GSON cannot otherwise get the type of a generic collection from the class data.
And one to represent the overall JSON message:
public class InfoMessage {
public InfoItemList Info;
public InfoMessage() {};
}
And then just:
gson.fromJson(jsonString, InfoMessage.getClass());
If just de-serializing a collection:
Type listType = new TypeToken<List<InfoItem>>() {}.getType();
gson.fromJson(jsonString2, listType);
The Info object is a list because of the []. You have to use the following code to deserialze it:
EDIT:
public class Info {
// as in your question
public String name;
...
}
public class Data {
#SerializedName("Info")
public List<Info> info;
}
Then just use the data class to deserialize your json.

Categories