I'm trying to add a new JSON object inside cars.json in "carTypes"
How would I go about doing this?
Im able to fetch data from cars.json but don't know how to add data to it
My current cars.json file
"carTypes": [
{
"model": "toyota",
"make": "corolla",
"year": "2005"
}
],
How I want it to be
"carTypes": [
{
"model": "toyota",
"make": "corolla",
"year": "2005"
},
{
"model": "civic",
"make": "honda",
"year": "2017"
}
],
Assuming you have an ObjectMapper:
ObjectMapper mapper = new ObjectMapper();
and you already have the content of your first snippet inside a JsonNode that you loaded from somewhere,
JsonNode carTypes = mapper.readTree(...);
then you should:
ArrayNode array = (ArrayNode) jsonNode.get("carTypes"); //<-- 1) convert the node into ArrayNode
ObjectNode objNode = mapper.createObjectNode(); //<-- 2) create a new object node
objNode.put("model", "civic"); //<-- add your attributes to the new object node
array.put(objNode); //<-- put the new node inside the array
Then you can convert your array back to JsonNode and do whatever you want with your Json.
If you use org.json and have loaded the JSON:
JSONObject obj = new JSONObject(jsonStr);
Then you can get to the "carTypes" array and add the new element:
JSONArray arr = obj.getJSONArray("carTypes");
JSONObject hondaCivic17Json = new JSONObject()
.put("model", "civic")
.put("make", "honda")
.put("year", "2017");
JSONArray newArray = arr.put(hondaCivic17Json);
JSONObject newJson = obj.put("carTypes", newArray);
String newJsonStr = newJson.toString();
System.out.println(newJsonStr);
Output:
{
...
"carTypes":
[
{"year":"2005","model":"toyota","make":"corolla"},
{"year":"2017","model":"civic","make":"honda"}
]
...
}
You can override the file like this:
Files.write(path, newJson.toString().getBytes());
Related
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.
I am working on a Java Spring boot api.
when the the call is made to get /api/home
I want to return this json sample structure.
var response = [
{
"type": "profile-breakdown",
"order": 0,
"grid-width": 6,
"grid-background": "",
"grid-background-url": "",
"title": "",
"contents": {
"name": "Name1",
"avatar" : 1,
"nextSDQ": 4,
"SQDCount": 3
}
},
{
"type": "current-standing",
"order": 1,
"grid-width": 6,
"grid-background": "",
"grid-background-url": "",
"title": "Your current standing summary",
"contents": {
"0": ["emotional distress", "behavioural difficulties", "hyperactivity and concentration difficulties", "difficulties in getting along with other young people"],
"4": ["kind and helpful behaviour"]
}
}
]
--
I've been building the various functions to get "profile-breakdown" and "current-standing" -- I want to append the responses to these to mimic the above structure.
so in MyService where /api/home gets RequestMapped to I begin to hook into my class MyApiHome
MyApiHome myApiHome = new MyApiHome();
JSONObject homeObj = myApiHome.getHomeData();
in MyApiHome -- I want to make "homeObj" in getHomeData an array as opposed to an JSONOBject - but then I start to fall into trouble with casts etc.. I want to build this in such a way - that if getProfileBreakDown is null or decoupled it isn't appended to the homeObj.
public class MyApiHome {
#SuppressWarnings("unchecked")
public JSONObject getHomeData(){
//build clean home object
JSONObject homeObj = new JSONObject();
homeObj.put("profile", this.getProfileBreakDown());
homeObj.put("currentstanding", this.getCurrentStanding());
//HashMap<List<String>, Object> hashMap = new HashMap<List<String>, Object>();
//hashMap.put())
return homeObj;
}
#SuppressWarnings("unchecked")
public Object getProfileBreakDown(){
//build clean home object
JSONObject contents = new JSONObject();
contents.put("name", "Name1");
contents.put("avatar", 1);
contents.put("nextSDQ", 4);
contents.put("SQDCount", 3);
//build clean home object
JSONObject json = new JSONObject();
json.put("type", "profile-breakdown");
json.put("order", 0);
json.put("grid-width", 6);
json.put("grid-background", "");
json.put("grid-background-url", "");
json.put("title", "");
json.put("contents", contents);
return json;
}
#SuppressWarnings("unchecked")
public Object getCurrentStanding(){
String[] stressArray1 = {"emotional distress", "behavioural difficulties", "hyperactivity and concentration difficulties", "difficulties in getting along with other young people"};
String[] stressArray2 = {"kind and helpful behaviour"};
//build clean home object
JSONObject contents = new JSONObject();
contents.put("0", stressArray1);
contents.put("4", stressArray2);
//build clean home object
JSONObject json = new JSONObject();
json.put("type", "current-standing");
json.put("order", 1);
json.put("grid-width", 6);
json.put("grid-background", "");
json.put("grid-background-url", "");
json.put("title", "Your current standing summary");
json.put("contents", contents);
return json;
}
}
To create an array of JSONs, we need to use JSONArray object which has a list of JSONObjects.
So using JSONArray.
I add to a json blob like a data stack.
JSONArray homeObj = new JSONArray();
if(this.getProfileBreakDown() != null){
homeObj.add(this.getProfileBreakDown());
}
if(this.getCurrentStanding() != null){
homeObj.add(this.getCurrentStanding());
}
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).
I am trying to use JsonObject to convert the java object to String. Following is the code that i am using to add the properties :
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("id", favoriteWrapper.getId());
jsonObject.addProperty("menuitemid", favoriteWrapper.getMenuItemId());
jsonObject.addProperty("displayname", favoriteWrapper.getDisplayName());
jsonObject.addProperty("description", favoriteWrapper.getDescription());
jsonObject.addProperty("alias", favoriteWrapper.getAlias());
Gson gson = new Gson();
jsonObject.addProperty("condiments", gson.toJson(favoriteWrapper.getCondiments()));
Here the last property condiments is a list of Long values and following is the response retrieved:
[
{
"id": 1,
"menuitemid": 1,
"displayname": "Ham",
"description": "Ham",
"alias": "Ham",
"condiments": "[1,8,34,2,6]"
}
]
Expected output is as following which is different for condiments:
[
{
"id": 1,
"menuitemid": 1,
"displayname": "Ham",
"description": "Ham",
"alias": "Ham",
"condiments": [1,8,34,2,6]
}
]
What should I do to get the condiments as JSON array rather than String ?
I found the answer to my problem. I used JsonArray and JsonPrimitive to achieve the required response:
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("id", favoriteWrapper.getId());
jsonObject.addProperty("menuitemid", favoriteWrapper.getMenuItemId());
jsonObject.addProperty("displayname", favoriteWrapper.getDisplayName());
jsonObject.addProperty("description", favoriteWrapper.getDescription());
jsonObject.addProperty("alias", favoriteWrapper.getAlias());
JsonArray condiments = new JsonArray();
for (Long condimentId : favoriteWrapper.getCondiments()) {
condiments.add(new JsonPrimitive(condimentId));
}
jsonObject.add("condiments", condiments);
jsonObjects.add(jsonObject);
I am trying to parse json output from neo4j in java as:
Object obj = parser.parse(new FileReader("D:\\neo4j.json"));
JSONArray json = (JSONArray) obj;
System.out.println(json.size());
for (int i = 0; i < json.size(); i++) {
JSONObject jsonObject = (JSONObject) json.get(i);
String data = (String);
jsonObject.get("outgoing_relationships");
String name = (String) jsonObject.get("name");
System.out.println(data);
System.out.println(name);
}
Can somebody help me to get values inside "data" element:
I have json output from neo4j as follows:
[{
"outgoing_relationships": "http://host1.in:7474/db/data/node/133/relationships/out",
"data": {
"MOTHERS_NAME": "PARVEEN BAGEM",
"MOBILE_NO": "9211573758",
"GENDER": "M",
"name": "MOHD",
"TEL_NO": "0120-",
"PINCODE": "110001"
},
"traverse": "http://host1.in:7474/db/data/node/133/traverse/{returnType}",
"all_typed_relationships": "http://host1.in:7474/db/data/node/133/relationships/all/{-list|&|types}",
"property": "http://host1.in:7474/db/data/node/133/properties/{key}",
"self": "http://host1.in:7474/db/data/node/133",
"properties": "http://lhost1.in:7474/db/data/node/133/properties",
"outgoing_typed_relationships": "http://host1.in:7474/db/data/node/133/relationships/out/{-list|&|types}",
"incoming_relationships": "http://host1.in:7474/db/data/node/133/relationships/in",
"extensions": {
},
"create_relationship": "http://host1.in:7474/db/data/node/133/relationships",
"paged_traverse": "http://host1.in:7474/db/data/node/133/paged/traverse/{returnType}{?pageSize,leaseTime}",
"all_relationships": "http://host1.in:7474/db/data/node/133/relationships/all",
"incoming_typed_relationships": "http://host1.in:7474/db/data/node/133/relationships/in/{-list|&|types}"
}]
Regards,
Jayendra
You can try following way. Inside the for loop get the data node as JSONObject. From that data node you can extract every property. I just extracted mother name from data.
JSONObject data = (JSONObject) jsonObject.get("data");
final String motherName = (String) data.get("MOTHERS_NAME");
What library are you using to parse JSON ? I'd recommend that you use Jackson
For eg: To get the data you read from the file in a Map, you can write a method like this.
#SuppressWarnings("rawtypes")
public static Map toMap(Object object) throws JsonProcessingException{ ObjectMapper mapper = new ObjectMapper();
return mapper.convertValue(object, Map.class);
}