Save JSON request as Item in dynamoDb - java

I have a request of the following JSON format:
{
"profile": {
"created": 1505202655,
"createdBy": "abc",
"updated": 1505202655,
"updatedBy": "xyz"
},
"likesId": [
"0010127916"
],
"icon": null,
"Attributes": {
"backgroundColor": "#FFFFFF",
"logo": "images/Logos/P0010127916.jpg",
"textColor": "#000000"
},
"profileId": "PACYG0010916",
"restrictions": {
"clients": [
"Android",
"SmartTv"
],
"UserTypes": [
"user1",
"user2"
],
"periodEnd": 1512978849,
"periodStart": 1505202849
},
}
I am trying to save the above JSON request Object in the dynamoDb table using putItem. However I am stuck in some issues which are as follows:
Can I store this whole JSON request as-is(without escaping double quotes) in the form of item in dynamodb table?
In case of likesId and Attributes I am storing them as a List and Map with the help of .withList and .withMap methods respectively, but in case of profile I have taken it as a POJO which has 4 states, how can I save this object with the putItem as I did not find any method for saving objects like this, as we have methods for string, numbers and other datatypes, how can I save my own object?
Any kind of guidance will be highly appreciated as I am new to dynamoDb and learning it by doing POC.

You should be able to save it quite easily with the DocumentClient class:
http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#put-property
var params = {
TableName : 'Table',
Item: item
};
var documentClient = new AWS.DynamoDB.DocumentClient();
documentClient.put(params, function(err, data) {
if (err) console.log(err);
else console.log(data);
});
Where item is the object from your original question

Related

Generate models and serializers from JSON with null value and missing attributes?

i am trying to generate a class model from an APIs JSON response (List), i use some service for auto-generation, and everything seems to work fine until the response JSON start returning attributes with a null value and the other thing is that some attributes are missing when i call the APIs. EX:
response JSON:
[
{
"persone": {
"name": "To John",
"age": 15
},
"group": "ipsum"
},
{
"persone": {
"name": "To John",
"age": null
},
"group": "ipsum"
},
{
"persone": {
"name": "To John"
}
}
]
in the above example, the age attribute is null, and the group attribute is missing in the last object of the list.
My question is how do you create an appropriate class model in that case handling the null and the missing attribute?

Get json object in Array based on key and value in Java

I have a Json body like the example below. I need to extract the value from a key that has another key with a specific value in an array. I am passing in a JsonNode with everything in the detail component of the message, I can easily extract from each level, however, I'm struggling with the array.
In this case, I need to extract the value of "value" (Police/Fire/Accident Report) from the object in the array which has a key/value pair of "name":"documentTitle". I understand this is a JSONArray, but I can't find a good example that shows me how to extract the values for an object in the array that contains a certain key/value pair, I don't think I can rely on getting the object in position [2] in the array as the same objects may not always be present in the additionalMetadata array.
Sample Json:
"sourceVersion": "1.0",
"eventId": "8d74b892-810a-47c3-882b-6e641fd509eb",
"clientRequestId": "b84f3a7b-03cc-4848-a1e8-3519106c6fcb",
"detail": {
"stack": "corona",
"visibilityIndicator": null,
"documentUid": "b84f3a7b-03cc-4848-a1e8-3519106c6fcb",
"additionalMetadata": [
{
"name": "lastModifiedDate",
"value": "2021-05-21T04:53:53Z"
},
{
"name": "documentName",
"value": "Police/Fire Report, 23850413, 2021-05-20 14:51:23"
},
{
"name": "documentTitle",
"value": "Police/Fire/Accident Report"
},
{
"name": "documentAuthor",
"value": "System Generated"
},
{
"name": "lastModifiedBy",
"value": "System Updated"
},
{
"name": "createdBy",
"value": "System Generated"
},
{
"name": "documentDescription",
"value": "Police/Fire Report received"
},
{
"name": "organizationCode",
"value": "Claims"
}
]
}
}```
Loop through the json array and extract the json object with name documentTitile. From that json object you can get the value
Well, either the JSON framework you're using supports this out of the box (check the documentation) or you could convert it manually to a map:
List<AdditionalMetadataEntry> additionalMetadata;
[...]
Map<String, String> additionalMetadataMap = additionalMetadata.stream().collect(Collectors.toMap(AdditionalMetadataEntry::getName, AdditionalMetadataEntry::getValue));
I was able to figure it out. I created a new node off the existing notificationBody JsonNode, then parsed through the metadata key/value pairs:
String docTitle = "";
JsonNode additionalMetadata = notificationBody.get("detail").get("additionalMetadata");
for (JsonNode node: additionalMetadata) {
String name = node.get("name").asText();
String value = node.get("value").asText();
if(name.equals("documentTitle")){
docTitle = value;
}
}

Is it possible to get the values from Json object with limit

I have a Json object like this in my Postgres DB:
{
"emails": [
{
"email": {
"id": "e8dc927f-679d-496b-85fb-465edf35c676",
"value": "hello#gmail.com"
}
},
{
"email": {
"id": "1b78758a-abc4-46ef-9de9-c999a0c8c418",
"value": "hello1#gmail.com"
}
}
],
"lastName": {
"id": "718109fd-2d00-475a-829a-c8af9a7f0067",
"value": "lastName"
},
"firstName": {
"id": "6c46a5b3-6f89-4692-a214-4943de22018d",
"value": "firstName"
},
}
And so on big json with around 1000 elements, now I want to parse and get the first 500 elements from json and make another json. what I mean by element here is anything which has Id is a element. For example firstName , LastName, email, email are the elements not the emails. I tried Jackson api but couldn't find a way how to count the elements and make a json exactly like above and return. and when I do any modifications in the first 500 elements I should save the Json with edits. Any help is much appreciated. I even tried postgres array_agg(e) function but that is only accepting only array.

Jackson converting dynamic json to map

I have a problem where some structure of the json is fixed while some part is dynamic. The end output has to be an object of type
Map<String,List<Map<String,String>>>
I am pasting a sample json code for which the jackson work -
{
"contentlets": [
{
"template": "8f8fab8e-0955-49e1-a2ed-ff45e3296aa8",
"modDate": "2017-01-06 13:13:20.0",
"cachettl": "0",
"title": "New Early Warnings",
"subscribeToListIi": "am#zz.com",
"inode": "15bd497-1d8e-4bc7-b0f4-c799ed89fdc9",
"privacySetting": "public",
"__DOTNAME__": "New gTLD Early Warnings",
"activityStatus": "Completed",
"host": "10b6f94a-7671-4e08-9f4b-27bca80702e7",
"languageId": 1,
"createNotification": false,
"folder": "951ff45c-e844-40d4-904f-92b0d2cd0c3c",
"sortOrder": 0,
"modUser": "dotcms.org.2897"
}
]
}
ObjectMapper mapper = new ObjectMapper();
Map<String,List<Map<String,String>>> myMap=mapper.readValue(responseStr.getBytes(), new TypeReference<HashMap<String,List<Map<String,String>>>>() {});
The above code is working fine but when the json changes to (basically a metadata tag is added) it is not able to convert to map.
{
"contentlets": [
{
"template": "8f8fab8e-0955-49e1-a2ed-ff45e3296aa8",
"modDate": "2017-01-06 13:13:20.0",
"cachettl": "0",
"title": "New gTLD Early Warnings",
"subscribeToListIi": "aml#bb.com",
"inode": "15bd4057-1d8e-4bc7-b0f4-c799ed89fdc9",
"metadata": {
"author": "jack",
"location": "LA"
},
"privacySetting": "public",
"__DOTNAME__": "New gTLD Early Warnings",
"activityStatus": "Completed",
"host": "10b6f94a-7671-4e08-9f4b-27bca80702e7",
"languageId": 1,
"createNotification": false,
"folder": "951ff45c-e844-40d4-904f-92b0d2cd0c3c",
"sortOrder": 0,
"modUser": "dotcms.org.2897"
}
]
}
This is expected since the type of the value of metadata is not a String. If you change the type of the map accordingly then it works:
Map<String,List<Map<String,Object>>> myMap = mapper.readValue(reader, new TypeReference<HashMap<String,List<Map<String,Object>>>>() {});
Of course you are left with the problem that values in the map are not of the same type. so you need to ask yourself what is the desired data structure you want and how you further process it. However, one cannot deserialize a json structure into a simple String.

Ignore Null Value Fields From Rest API Response Java

In my project when i send Rest Response to Advance Rest Client It only shows Fields which Have some values and Ignores(Does not show) fields which have NULL Values or Empty values.
Part Of Code:
Gson gson=new Gson();
// firstResponse is Object which contains the values
String jsonString = gson.toJson(firstResponse);
test.saveJson(jsonString); //OR System.out.println(jsonString);
return Response.ok(firstResponse).build(); // Response to Rest Client
Response sample To return Response.ok(firstResponse).build();
Advance rest client From web project :
{
"Name": "smith",
"Properties": {
"propertyList": [
{
"ID": "072",
"Number": "415151",
"Address": "Somewhere"
},
{
"ID": "151",
"Number": "a800cc79-99d1-42f1-aeb4-808087b12c9b",
"Address": "ninink"
},
{
"ID": "269",
},
],
},
}
Now when i save this as Json String in DB or When i want to Print this to console it also prints the fiels with null or empty values:
{
"Name": "smith",
"Properties": {
"propertyList": [
{
"ID": "072",
"Number": "415151",
"Address": "Somewhere"
},
{
"ID": "151",
"Number": "a800cc79-99d1-42f1-aeb4-808087b12c9b",
"Address": "ninink"
},
{
"ID": "269",
"Number": "",
"Address": ""
},
],
},
"resultList" :[]
}
How can i print or save this JSON string same as response in rest client i.e. i dont want to print null or empty value field i just want to ignore them.
in top og entity class , try with the annotation
#JsonInclude(Include.NON_EMPTY)
this annotation don't show any empty field in your json.
Not giving you a code but here are some pointers for you:
Read the manual: How to handle NULL values
You may need to use a custom exclusion strategy
Also read this Q&A: Gson: How to exclude specific fields from Serialization without annotations

Categories