Adding changes to the JSON structure - java

I have the following JSON, generated in the Android application:
{
"Details": {
"ClaimDate": "08/10/2019",
"HFCode": "55555"
},
"Items": [
{
"Item": {
"ItemCode": "Y203",
"ItemPrice": "20",
"ItemQuantity": "1"
}
}
],
"Services": [
{
"Service": {
"ServiceCode": "X105",
"ServicePrice": "200",
"ServiceQuantity": "1"
}
}
]
}
On the server side, I need this structure
{
"details": {
"ClaimDate": "08/10/2019",
"HFCode": "55555"
},
"items": [
{
"itemCode": "Y200",
"itemPrice": 0,
"itemQuantity": 0
}
],
"services": [
{
"serviceCode": "X100",
"servicePrice": 0,
"serviceQuantity": 0
}
]
}
Is there a way to customize this on the Android application side?
I try to do it manually, but I can't get a satisfactory result

You can use a transformer function which will take the first json/object as input and returns the second json/object as output. Unfortunately, since your keys and data types are different, standard libraries will not able to do this. If you want to use Jackson or Gson, you will have to play with Custom (De) Serializers.

If you are using Jackson (One of the most popular JSON libraries) and you just want to transform the given JSON string into another one, then you can achieve this by following way:
ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(jsonStr);
ObjectNode rootNew = mapper.createObjectNode();
rootNew.put("details", root.get("Details"));
JsonNode itemNode = root.get("Items").get(0).get("Item");
ObjectNode itemsNodeNew = mapper.createObjectNode();
itemsNodeNew.put("itemCode", itemNode.get("ItemCode"));
itemsNodeNew.put("itemPrice", itemNode.get("ItemPrice"));
itemsNodeNew.put("itemQuantity", itemNode.get("ItemQuantity"));
rootNew.put("items", mapper.createArrayNode().add(itemsNodeNew));
JsonNode serviceNode = root.get("Services").get(0).get("Service");
ObjectNode serviceNodeNew = mapper.createObjectNode();
serviceNodeNew.put("serviceCode", serviceNode.get("ServiceCode"));
serviceNodeNew.put("servicePrice", serviceNode.get("ServicePrice"));
serviceNodeNew.put("serviceQuantity", serviceNode.get("ServiceQuantity"));
rootNew.put("services", mapper.createArrayNode().add(serviceNodeNew));
System.out.println(rootNew.toString());
But if you want to convert the JSON string to POJO for further manipulation, you can directly deserialize and serialize it.

Related

How to extract a particular value from Json Node?

Hi I have Input of JsonNode type as follows:
{
"Records": [
{
"EventSource": "aws:sns",
"EventVersion": "1.0",
"EventSubscriptionArn": "arn:aws:sns:us-west-1:270252992114:d1dd43d0-8bf1-496c-bc94-f4e70dec5032",
"Sns": {
"Type": "Notification",
"MessageId": "923d528f-c844-5d49-95de-018f6d583bfd",
"TopicArn": "arn:aws:sns:us-west-1:270252992114:",
"Subject": null,
"Message": "AAAAAQAAAAAAAAABAAAAJGNvbS5hbWF6b24uY3VzdG9tZXJldmVudC5jZXMudGVzdC5OQQAAABDW7HxyIs4PvuXtarSxIxdeAAABALZT+4Yv09z9tK48/miZ6IhjvVCLixiH3GLltCxQzEkNgf9NTD57G744vdnw1D3LxLmxT4i0CCkVJJ5IPaH3Ud5Oy6MKa5wRrldtS6MTDMzKqoPwcdMiLm3AogonUAqyBYrxWt8fHrCYIlggX9EFW9Dk9ugDRrJuhCZqfVnt/wRUyP33DycwRKHBHSxn1XuDi9ZyEeCxrMLn9rGmpVvUQb3mdFReoVDmP4cEWcQEwYxG6/WvyimHGD5JtSxzlCR3rwddu8vXlp9Mq127+scPipAm83IJSw7CS5laZQZAD8qR4WwSfSZw8kq72y/LulhzWj3w7jbtOtmhbdnPyIN+L4I=",
"Timestamp": "2018-02-16T09:22:36.149Z",
"SignatureVersion": "1",
"Signature": "f+23JQ6r9gZL6dRay4wqJHrX5CnB9cSVpPS/zgopPKHFOD5zvEpuTiGfuNf0e2L6/84pm6gK9xCEakzeaWtBAp7J/hFfbKQ2BSJ/GAKX1peG16Q8TS2k0NVxjzG4ImEHxf3i3ODOFJeA7WHxRZiMkNO+79lZDxkkOQdfWR3OEQ1yP8CjE4HLlLoSEUdk170AOw1nty9NZ6FOnsotLf5jce0GrXs1lkn7J/3nv/YlSqdMZEAR4SZDELCH3krQ4mUO7gwUfkDSFXsjWLarTayYl20eH3g/RZLQgPEQGTRBZW5wrknXg1vm4H4ICxxrGJBooAs7BCLkUVT1m4juRrlljA==",
"SigningCertUrl": "https://sns.us-west-1.amazonaws.com/SimpleNotificationService-433026a4050d206028891664da859041.pem",
"UnsubscribeUrl": "https://sns.us-west-1.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-west-1:270252992114:",
"MessageAttributes": {}
}
}
]
}
I want to extract value of TopicArn and Message, I tried following code but rawSns is coming as null:
JsonNode rawResource = input.get("Records");
logger.log("rawResource is: " + rawResource);
JsonNode rawSns = rawResource.get("Sns");
Does anyone can help me out in this?
You can use following:
JsonNode rawResource = input.get("Records");
logger.log("rawResource is: " + rawResource);
JsonNode rawSns = rawResource.get(0).get("Sns");
See here for Javadoc
This is precisely what you need.
var jsonObject = JSON.parse('{"Records":[{"EventSource":"aws:sns","EventVersion":"1.0","EventSubscriptionArn":"arn:aws:sns:us-west-1:270252992114:d1dd43d0-8bf1-496c-bc94-f4e70dec5032","Sns":{"Type":"Notification","MessageId":"923d528f-c844-5d49-95de-018f6d583bfd","TopicArn":"arn:aws:sns:us-west-1:270252992114:","Subject":null,"Message":"AAAAAQAAAAAAAAABAAAAJGNvbS5hbWF6b24uY3VzdG9tZXJldmVudC5jZXMudGVzdC5OQQAAABDW7HxyIs4PvuXtarSxIxdeAAABALZT+4Yv09z9tK48/miZ6IhjvVCLixiH3GLltCxQzEkNgf9NTD57G744vdnw1D3LxLmxT4i0CCkVJJ5IPaH3Ud5Oy6MKa5wRrldtS6MTDMzKqoPwcdMiLm3AogonUAqyBYrxWt8fHrCYIlggX9EFW9Dk9ugDRrJuhCZqfVnt/wRUyP33DycwRKHBHSxn1XuDi9ZyEeCxrMLn9rGmpVvUQb3mdFReoVDmP4cEWcQEwYxG6/WvyimHGD5JtSxzlCR3rwddu8vXlp9Mq127+scPipAm83IJSw7CS5laZQZAD8qR4WwSfSZw8kq72y/LulhzWj3w7jbtOtmhbdnPyIN+L4I=","Timestamp":"2018-02-16T09:22:36.149Z","SignatureVersion":"1","Signature":"f+23JQ6r9gZL6dRay4wqJHrX5CnB9cSVpPS/zgopPKHFOD5zvEpuTiGfuNf0e2L6/84pm6gK9xCEakzeaWtBAp7J/hFfbKQ2BSJ/GAKX1peG16Q8TS2k0NVxjzG4ImEHxf3i3ODOFJeA7WHxRZiMkNO+79lZDxkkOQdfWR3OEQ1yP8CjE4HLlLoSEUdk170AOw1nty9NZ6FOnsotLf5jce0GrXs1lkn7J/3nv/YlSqdMZEAR4SZDELCH3krQ4mUO7gwUfkDSFXsjWLarTayYl20eH3g/RZLQgPEQGTRBZW5wrknXg1vm4H4ICxxrGJBooAs7BCLkUVT1m4juRrlljA==","SigningCertUrl":"https://sns.us-west-1.amazonaws.com/SimpleNotificationService-433026a4050d206028891664da859041.pem","UnsubscribeUrl":"https://sns.us-west-1.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-west-1:270252992114:","MessageAttributes":{}}}]}');
console.log(((jsonObject["Records"][0])["Sns"])["TopicArn"]);
This online tool can help you understand the structure of your JSON : JSON viewer.

How to get count all json nodes using Jackson framework

Here is my user.json
{
"id":1,
"name":{
"first":"Yong",
"last":"Mook Kim"
},
"contact":[
{
"type":"phone/home",
"ref":"111-111-1234"
},
{
"type":"phone/work",
"ref":"222-222-2222"
}
]
},
{
"id":2,
"name":{
"first":"minu",
"last":"Zi Lap"
},
"contact":[
{
"type":"phone/home",
"ref":"333-333-1234"
},
{
"type":"phone/work",
"ref":"444-444-4444"
}
]
}
I would like count how many json object is in there. For example the above json has 2 json object id = 1 and id =2.
//tree model approach
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(new File("user.json"));
List<JsonNode> listOfNodes = rootNode.findParents("first");
System.out.println(listOfNodes.size());
Giving me size = 1.
Can you please tell me what i am doing wrong?
Thanks
Your java code is correct but your json file is invalid.
Jackson parses only first valid element ("Yong").
To fix this just add [ at the begining and ] at the end of file (make it array).

LibGDX Json parser - parse specific node/object

I'm currently implementing JSON parsing in my game but I've encountered a problem that I can't find a solution for: how do you parse a specific node/object (not sure what to call it) from a JSON file? Let's say my JSON looks like this:
{
"intro/credits": { //A node/object.
"title": "Intro music / Credits music",
"authors": [
{
"name": "Vindsvept",
"links": {
"YouTube": "https://www.youtube.com/channel/UCfSUheoljDlGDjerRylO4Nw",
"Bandcamp": "https://vindsvept.bandcamp.com/"
}
}
]
},
"extra": { //Another node/object.
"title": "extra",
"authors": [
{
"name": "extra",
"links": {
"linkTest": "linkTest"
}
}
]
}
}
With that JSON in mind, how would I do something like this?:
MyObject myObj = json.fromJson(parse.object.called.extra);
Thanks to Underbalanced I can now answer my own question: to exctract an object called extra you would do something like this:
Json json = new Json();
JsonValue root = new JsonReader().parse(Gdx.files.internal("path/to/your/file.json"));
JsonValue extra = root.get("extra"); //Replace 'extra' with whatever your object is called.
MyObject myObj = json.fromJson(MyObject.class, extra.toString());

read json file and parse inner json array in java

{
"vers": 0.01,
"config": {
"rate": "perhr",
"valueColumns": [
"vCPU",
"ECU",
"memoryGiB",
"storageGB",
"linux"
],
"currencies": [
"USD"
],
"regions": [
{
"region": "us-east",
"instanceTypes": [
{
"type": "generalCurrentGen",
"sizes": [
{
"size": "t2.micro",
"vCPU": "1",
"ECU": "variable",
"memoryGiB": "1",
"storageGB": "ebsonly",
"valueColumns": [
{
"name": "linux",
"prices": {
"USD": "0.013"
}
}
]
},
{
"size": "t2.small",
"vCPU": "1",
"ECU": "variable",
"memoryGiB": "2",
"storageGB": "ebsonly",
"valueColumns": [
{
"name": "linux",
"prices": {
"USD": "0.026"
}
}
]
}
]
}
]
}
]
}
}
Hi, i wanted to read this json file. I tried various ways from google but getting a null at valuesColumns. I have to read sizes array and have to put in list.
I think it will help your cause if you format your json. As it is it's quite hard to read. Googling for a JSON beautifier quickly found me this one.
When working with JSON your browser console provides a nice environment for inspecting and playing with the data. I pasted it into the browser console and did (hit enter after each line):
var x = { ... paste JSON here ... }
x
x.config
x.config.valueColumns
This tells me that x is a JSON object, config is a JSON object and valueColumns is a JSON array
Now to java. Grab yourself a json library, and accessing valueColumns will be something like:
JSONObject x = new JSONObject("{ ... JSON string ... }");
JSONObject config = x.getJSONObject("config");
JSONArray valueColumns = config.getJSONArray("valueColumns");
You can then iterate over valueColumns and pull out what you need.
Note that the above only gets you to the first valueColumns array under config. By following the same principle you can go deeper into the structure and get out the valueColumns for the objects in the sizes array if that's what you're really after.
For parsing json to java there are simple step.
Below code snippet may help you.
// parse json to java
Object obj = parser.parse(s);
JSONObject json = (JSONObject) obj;
JSONObject o = (JSONObject) json.get("config");
//get json array.
JSONArray array = (JSONArray) o.get("valueColumns");
System.out.println(array.toJSONString());
//access element by index
System.out.println(array.get(0));

How to get the value flag in JSON

I am new to JSON. I have the following JSON object
{
"data": [
{
"name": {
"id": 49,
"name": "basha",
"description": "",
"owner": "cpee",
"projectUsers": [],
"flag": null
},
"flag": "add"
}
]
}
I want to get the flag value ("add"), but I am getting null.
In java I am trying to get the value using this code:
org.codehaus.jackson.JsonNode
jsonNode.get("data").get("flag");
As requested, here is more of my Java code
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
ObjectMapper mapper = new ObjectMapper();
projectDTO = mapper.readValue(json.get("data").get(0), ProjectDetailsDTO.class);
readValue will parse the JSON object to Java specific object
json.get("data").get(0).get("flag");
data is an array with only 1 item. and in that item you can get flag by above expression
Data is an array...
org.codehaus.jackson.JsonNode
jsonNode.get("data")[0] .get("flag");
ObjectMapper mapper = new ObjectMapper();
projectDTO =mapper.readValue(json.get("data").get(0), ProjectDetailsDTO.class);
Flag=mapper.readValue(projectDTO.get("flag", ProjectDetailsDTO.class )) ;

Categories