How to add an JsonObject in a JsonArray at some random index - json

I am having a JsonAarray like below:
JsonARray ProfileTabs = [{"totalItemCount":0,"label":"Updates","name":"update"},{"totalItemCount":2,"label":"Members","url":"groups\/member\/list\/129","urlParams":[],"name":"members"},{"totalItemCount":5,"label":"Photos","url":"groups\/photo\/list","urlParams":{"group_id":129},"name":"photos"}]
As in the above JsonArray I am having 3 JsonObject at index 0, 1, 2.
Now I want to add a new JsonObject in this JsonArray at index 1.
So, I have created a new JsonObject as below:
JSONObject InfoTabJsonObject = new JSONObject();
InfoTabJsonObject.put("totalItemCount", 0);
InfoTabJsonObject.put("label", "Info");
InfoTabJsonObject.put("name", "info");
mProfileTabs.put(1, InfoTabJsonObject);
And added this JsonObject to the JsonArray at index 1, but after adding this JsonObject it replaces the original 1st index's JsonObject with the new one.
How can I achieve the index should remain properly, means that new one will be added to 1st index and the other one will adjust their index.
Please help me here, thanks in advanced.

Take a look at the below code, uses org.json.simple.JSONArray and org.json.simple.JSONObject.
JSONObject jsonObj1 = new JSONObject();
jsonObj1.put("totalItemCount", 0);
jsonObj1.put("label", "Updates");
jsonObj1.put("name", "update");
JSONObject jsonObj2 = new JSONObject();
jsonObj2.put("totalItemCount", 2);
jsonObj2.put("label", "Members");
jsonObj2.put("url", "groups/member/list/129");
JSONArray temp = new JSONArray();
jsonObj2.put("urlParams", temp);
jsonObj2.put("name", "members");
JSONObject jsonObj3 = new JSONObject();
jsonObj3.put("totalItemCount", 5);
jsonObj3.put("label", "Photos");
jsonObj3.put("url", "groups/photo/list");
JSONObject temp1 = new JSONObject();
temp1.put("group_id", 129);
jsonObj3.put("urlParams", temp1);
jsonObj3.put("name", "photos");
JSONArray array=new JSONArray();
array.add(jsonObj1); //adding objects into array
array.add(jsonObj2);
array.add(jsonObj3);
try {
// Writing to a file
System.out.println("Before addition of new object into array!");
File file=new File("test1.json");
file.createNewFile();
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(array.toJSONString());
fileWriter.flush();
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
JSONObject InfoTabJsonObject = new JSONObject();
InfoTabJsonObject.put("totalItemCount", 0); //adding objects into array
InfoTabJsonObject.put("label", "Info");
InfoTabJsonObject.put("name", "info");
array.add(1, InfoTabJsonObject);
System.out.println("After addition of new object into array!");
try {
// Writing to a file
File file=new File("test.json");
file.createNewFile();
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(array.toJSONString());
fileWriter.flush();
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
test1.json The orginal one before adding new object in array.
[
{
"name": "update",
"label": "Updates",
"totalItemCount": 0
},
{
"urlParams": [],
"name": "members",
"label": "Members",
"url": "groups\/member\/list\/129",
"totalItemCount": 2
},
{
"urlParams": {
"group_id": 129
},
"name": "photos",
"label": "Photos",
"url": "groups\/photo\/list",
"totalItemCount": 5
}
]
test.json The updated one after adding new object in array.
[
{
"name": "update",
"label": "Updates",
"totalItemCount": 0
},
{
"name": "info",
"label": "Info",
"totalItemCount": 0
},
{
"urlParams": [],
"name": "members",
"label": "Members",
"url": "groups\/member\/list\/129",
"totalItemCount": 2
},
{
"urlParams": {
"group_id": 129
},
"name": "photos",
"label": "Photos",
"url": "groups\/photo\/list",
"totalItemCount": 5
}
]

Related

Getting a value from a complex JSON file (multiple objects inside an object)

I am trying to get a value from a JSON file, however it is a complex JSON file and i'm not sure how to go about it.
The value is situated inside an object, that is inside another object, which inside another object.
The values I want to retrieve from the JSON file is "value" and "unit" situated inside the object "metric". I have been able to successfully retrieve the "name" value.
The JSON file:
{
"ingredients": [
{
"name": "breakfast sausage",
"image": "breakfast-sausage-links.jpg",
"amount": {
"metric": {
"value": 226.796,
"unit": "g"
},
"us": {
"value": 8,
"unit": "ounces"
}
}
},
I will also include the method that I parse the JSON from:
private void jsonParse(){
String url = "https://api.spoonacular.com/recipes/"+ rMealId + "/ingredientWidget.json?&apiKey=da7dd16a704f4552b70a96c1e9641b08";
RequestQueue requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("ingredients");
for(int i = 0; i < jsonArray.length(); i++){
JSONObject ingredients = jsonArray.getJSONObject(i);
String iName = ingredients.getString("name");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Log.e("Volley", error.toString());
}
});
requestQueue.add(request);
}
Just focusing on your json string, try this:
let ings =
{
"ingredients": [
{
"name": "breakfast sausage",
"image": "breakfast-sausage-links.jpg",
"amount": {
"metric": {
"value": 226.796,
"unit": "g"
},
"us": {
"value": 8,
"unit": "ounces"
}
}
}
]
}
let jp = require('jsonpath');
let eat = jp.query(ings, '$..metric.*');
console.log(eat);
output:
[ 226.796, 'g' ]

How to concatenate / append a JsonObject to a JsonArray

Given the following code which gets called variously in the code, and then gets written to a file (separate method), I simple need to append the next value into the array. This is probably a simple Collections question but wasn't sure if there was a specialized Gson way of doing this:
public static void metricAsJSON(String testName, long testTime) {
Date date = new Date();
Timestamp ts = new Timestamp(date.getTime());
JSONObject obj = new JSONObject();
obj.put("testname", testName);
obj.put("Duration", testTime);
obj.put("Timestamp", ts.toString());
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(obj.toJSONString());
jsoncontent = gson.toJson(je);
JsonArray jsonArray = new JsonArray();
jsonArray.add(je);
jsoncontent = gson.toJson(jsonArray);
}
public static JsonArray appendMetricAsJson(String jsoncontent){
JsonArray jsonContentList = new JsonArray();
jsonContentList.add(jsoncontent);
return jsonContentList;
FileWriter fw1 = new FileWriter(f1, true);
PrintWriter pw1 = new PrintWriter(fw1);
if (f1.exists() && f1.isFile()) {
pw1.println(jsonContentList);
pw1.flush();
pw1.close();
fw1.close();
}
}
Current output:
[
{
"Duration": 30,
"testname": "Shopping link click to dropdown display time:",
"Timestamp": "2019-10-15 09:47:53.804"
}
]
Desired output:
[
{
"Duration": 30,
"testname": "Shopping link click to dropdown display time:",
"Timestamp": "2019-10-15 09:45:13.334"
},
{
"Duration": 16,
"testname": "Clothing link click to dropdown display time",
"Timestamp": "2019-10-15 09:44:34.356"
},
{
"Duration": 24,
"testname": "Toys link click to dropdown display time",
"Timestamp": "2019-10-15 09:46:33.453"
},
{
"Duration": 34,
"testname": "Electrics link click to dropdown display time",
"Timestamp": "2019-10-15 09:47:53.566"
}
]

How to create a JSON structure for this

Can you tell me how to create a Json objecct for this
I think it is a JSON with children JSON objects.
[{
"data": {
"ID": "56e819a90111257894be41c9e310f8cb",
"name": "Email_____2016-03-15 10_18_16",
"objCode": "DOCU",
"description": null,
"lastUpdateDate": "2016-03-15T10:18:17:551-0400"
}
}: null]
I did this
JSONObject childVal = new JSONObject();
JSONObject parent = new JSONObject();
try {
childVal.put("ID", "56e819a90111257894be41c9e310f8cb");
childVal.put("name", "Email_____2016-03-15 10_18_16");
childVal.put("objCode", "DOCU");
childVal.put("description", "null");
childVal.put("lastUpdateDate", "2016-03-15T10:18:17:551-0400");
parent.put("data", childVal);
but how do i get the parent [ object : null]
thanks

How to create new JSON from JSON?

I have a JSON consisting of the following data:
{
"comment": {
"S": "Nice"
},
"id": {
"S": "1ca38300-8938-11e5-8656-9bf2d3249757"
},
"postId": {
"S": "083c1f50-8b84-11e5-9021-7da869825160"
},
"spam": {
"N": "0"
},
"tags": {
"L": [
{
"S": "test1"
},
{
"S": "test2"
}
]
}
}
And now, I want to format the above JSON to the following format, like:
{
"comment":"Nice",
"id":"1ca38300-8938-11e5-8656-9bf2d3249757",
"postId":"083c1f50-8b84-11e5-9021-7da869825160",
"tags":["test1","test2"]
}
Load your json and manipulate like a plain object and then save it.
Here is how to transform your object:
var newObj = {
comment: oldObj.comment.S,
id: oldObj.id.S,
postId: oldObj.postId.S,
tags: oldObj.tags.L.map(function (entry) {
return entry.S;
})
}
Hey find the below code
suppose ur above jsonObject is completely names are and placed under result Object.
JSONObject obj = new JSONObject();
obj.put("comment",result.getJSONObject("comment").getString("s"));
obj.put("id",result.getJSONObject("id").getString("s"));
obj.put("postId",result.getJSONObject("postId").getString("s"));
List<String> test = new ArrayList<String>;
JSONArray js = result.getJSONObject("tags").getJSONArray("L");
for(I=o;i<js.length();I++){
test.add(js.get(i).getString("s"));
}
obj.put("tags",test);

How to pass list of objects in json object

Hi I am developing small application in which I am trying to pass some data in http post method. So I want to send my data like this form
"storeid": "151",
"floordata": {
"entry": [
10,
15
],
"exit": [
10,
15
],
"section": [
{
"id": "0",
"sectionname": "ABC",
"category": "office",
"boundary": [
[
85,
258
],
[
85,
298
],
[
125,
298
],
[
125,
258
],
[
85,
258
]
"description": "Mobile based company"
}
]
},
"category": null,
"description": null
so my problem is regarding section parameter. I am doing this for section parameter.
String section = "section=";
// Problem for me is here ...
JSONArray sections = new JSONArray();
List<List<Float>> sectionCords = new ArrayList<List<Float>>();
List<Float> sectionCordData = new ArrayList<Float>();
sectionCordData.add(0.0f);
sectionCordData.add(0.1f);
List<Float> sectionCordData1 = new ArrayList<Float>();
sectionCordData1.add(0.0f);
sectionCordData1.add(0.1f);
sectionCords.add(sectionCordData);
sectionCords.add(sectionCordData1);
JSONObject sectionObj = new JSONObject();
//List<JSONObject> cordList = new ArrayList<JSONObject>();
try {
sectionObj.put("category", "office");
sectionObj.put("description", "Mobile based company");
sectionObj.put("sectionname", "mobiotics");
sectionObj.put("id", 0);
sectionObj.put("boundary", sectionCords); // Check Here i am sending as list ...
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sections.put(sectionObj);
section += sections;
section +="&";
But In actual it my section boundary parameter going as string instead of list. Like this
boundary=[
[
0.0,
0.1
],
[
0.0,
0.1
]
],storeid=156&floor=2&section=[
{
"id": 0,
"sectionname": "mobiotics",
"category": "office",
"boundary": "[[0.0, 0.1], [0.0, 0.1]]", // See here is my problem ...
"description": "Mobile based company"
}
],entry=[
10,
15
],exit=[
10,
15
]
How to send it as list instead of string. Need Help. Thank you.
Define sectionChords, and sectionCordData* as JSONArray instead of List:
JSONArray sectionChords = new JSONArray();
JSONArray sectionCordData = new JSONArray();
sectionCordData.put(0.0f);
sectionCordData.put(0.1f);
JSONArray sectionCordData1 = new JSONArray();
sectionCordData1.put(0.0f);
sectionCordData1.put(0.1f);
sectionCords.put(sectionCordData);
sectionCords.put(sectionCordData1);
It must do what you want according to docs.
Put a key/value pair in the JSONObject, where the value will be a JSONArray which is produced from a Collection.
But it puts JSON representation of your object as String. So you should use either JSONArrays or Java objects. You should not mix them.
controller :
public JsonResult Index()
{
List<Location> location = (from a in db.Locations select a).ToList();
return Json(location, JsonRequestBehavior.AllowGet);
}