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
Related
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"
}
}
I have below json
[{
"Maindata": "{\"SubData\":[{\"Name\":\"a\",\"rollnumber\":1,\"ParentName\":c},{\"Name\":\"b\",\"rollnumber\":2,\"ParentName\":d},{\"Name\":\"m\",\"rollnumber\":3,\"ParentName\":n}],\"schooltime\":123213,\"lunchtime\":2321,\"TeacherName\":\"abc\",\"ClassTeacherName\":\"abc\",\"Subjects\":null,\"ClassName\":\"xyz\",\"PrincipleName\":[\"sdffd\"],\"ClassID\":\"21312\",\"books\":\"\",\"classdata\":{\"scienceclass\":\"2hrs\",\"Projects\":\"True\",\"Games\":\"Nothing\"},\"real\":null,\"classuniqueid\":\"21323234234\",\"schoolbelltime\":21323321}"
}]
In above Json we have
MainData - Main data has two main sections
SubData
ClassData
When i tried to view the above Json viewer it displays MainData as main Json and doesnot display sub data json
Now i want to convert above json to Pojo class, in a way say if i give Name of Subdata as "a" it should give me all details of "a". Now Subdata is dynamic, it has three sections now, it can have 100 when new students data are available or it can have only two. How to write a pojo class which reads this and gives data.
I am using gson and Below is my pojo class
public class MyPojo
{
private String Maindata;
public String getMaindata ()
{
return Maindata;
}
public void setMaindata (String Maindata)
{
this.Maindata = Maindata;
}
#Override
public String toString()
{
return "ClassPojo [Maindata = "+Maindata+"]";
}
}
You can use Jackson to convert JSON data to POJOs and POJOs to JSON data.
For complex JSON data like yours, you will need to create ArrayLists of complex types in your corresponding classes.
Paste your valid JSON into this site and select
Target language: Java
Annotation Style: GSON
and download the Zip file, extract it after that you get all POJO classes of your JSON response
I am trying to map the following response:
{
"data": {
"id": "1574083",
"username": "snoopdogg",
"full_name": "Snoop Dogg",
"profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_1574083_75sq_1295469061.jpg",
"bio": "This is my bio",
"website": "http://snoopdogg.com",
"counts": {
"media": 1320,
"follows": 420,
"followed_by": 3410
}
}
into an object where I only want to retrieve the username, full_name, and id fields.
Ex: something like:
public class User{
String id;
String username;
String full_name;
// getters + setters
}
Is there a way of doing this without first having to store the data object into a Map?
Use Jackson API. It should be simple:
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(jsonString, User.class); //jsonString is your actual json string.
You might want to tweak your User class to match the JSON string. E.g. your user class needs to have a 'data' field as List<Data> data; where 'Data' is another POJO. You can add the "id", "userName", etc fields in the 'Data' pojo.
You can either do it by hand via, for example, regexp or utilize any of JSON libraries like Jackson, GSON etc.
With GSON it's pretty simple. Say your json is stored in a String jsonString variable.
Gson gson = new Gson();
YourObject = gson.fromJson(jsonString, YourObject.class);
Although I'm not sure what will happen, since your jsonString doesn't have a key called User. However, this should work if you first extract data from your jsonString and name your POJO Data.
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.
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()