This question already has answers here:
JSONObject : Why JSONObject changing the order of attributes [duplicate]
(3 answers)
Closed 7 years ago.
When you add data in JSONObject it will store in it's own way.
Here is the Example of what i am trying to convey.
JSONObject obj = new JSONObject();
obj.put("metricname", "splunk-ui");
obj.put("timestamp", 1234567890);
obj.put("value",34);
System.out.println(obj);
Above code snippet will give below output.
{
"metricname": "splunk-ui",
"value": 34,
"timestamp": 1234567890
}
Here is the Problem :-
I add data in this sequence :- metricname , timestamp , value
This is the display sequence :- metricname , value , timestamp
So , how do i enforce my data adding sequence in JSONObject ??
FYI :- Doing this is mendatory as i will pass this JSON object to another API which can scan data in metricname , timestamp , value only.
HERE I AM POSTING CODE SNIPPET WHICH I USED FOR SOLVING THIS PROBLEM :-
I have used GSON library and this link to make this code work.
GSON Documention
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("metric", "mihirmonani");
jsonObject.addProperty("timestamp", 1346846400);
jsonObject.addProperty("value", 14);
JsonArray jArray = new JsonArray();
JsonObject jObject = new JsonObject();
jObject.addProperty("host", "splunk");
jObject.addProperty("host1", "splunk1");
jsonObject.add("tags",jObject);
System.out.println(jsonObject);
You can't with a JSONObject the only way to keep the order is using a JSONArray
[
{"name" : "metricname", "value" : "splunk-ui"},
{"name" : "value", "value" : 34},
{"name" : "timestamp", "value" : 1234567890}
]
Short answer: you can't. JSONObject uses a HashMap internally, which returns values depending on the order of the hash code.
You could use JSONWriter to write the values explicitly.
EDIT: To clarify, as Manu pointed out, you cannot retrieve the order after the values have been put in the JSONObject. My suggestion was to not put the values in the JSONObject to begin with, but use JSONWriter to write the values directly.
Related
I'm currently trying to process some JSON but it's given me an error saying that "Index 0 out of range [0..0)" the affected line is the one that is commented out.
JSONObject parentObject3 = new JSONObject(finalJSON3);
JSONArray parentArray3 = parentObject3.getJSONArray("players");
//JSONObject finalObject3 = parentArray3.getJSONObject(0);
tempGameBans = finalObject3.getInt("NumberOfBans");
tempVacBans = finalObject3.getInt("NumberOfMutes");;
Here is my JSON:
{
"players": [
{
"userID": "5648131",
"NumberOfBans": 0,
"NumberOfMutes": 1,
}
]
}
Edit: Currently I am only looking for 1 object per JSON URL so the Index should always be 0, unlike the possible duplicate which seems to be looking for multiple objects.
Edit 2: I found out what the issue is and it's due to the JSON not being correctly sent from my server. Thanks for the help anyway guys.
String jsonString = new String("{\"players\": [{\"userID\": \"5648131\",\"NumberOfBans\": 0,\"NumberOfMutes\": 1}]}");
JSONObject parentObject3 = new JSONObject(jsonString);
JSONArray parentArray3 = parentObject3.getJSONArray("players");
JSONObject finalObject3 = parentArray3.getJSONObject(0);
System.out.println(finalObject3.getInt("userID"));
System.out.println(finalObject3.getInt("NumberOfBans"));
System.out.println(finalObject3.getInt("NumberOfMutes"));
This is working fine, so there has to be some another issue.
You are calling some attribute either not in the JsonObject or the attribute value at that specified index doesn't exist.
Try remove the "," at the end of "NumberOfMutes": 1,.
I have a large file with many JSON objects similiar to the following. I need to parse everything to get the "bought_together" items as an array using the org.json library. I'm having trouble accessing anything nested in "related".
What is the required code to retrieve "bought_together" as a list?
{
"asin": "11158732",
"title": "Girls Ballet Tutu Zebra Hot Pink",
"price": 3.17,
"imUrl": "http://ecx.images-amazon.com/images/I/51fAmVkTbyL._SY300_.jpg",
"related":
{
"also_bought": ["L00JHONN1S", "B002BZX8Z6"],
"also_viewed": ["F002BZX8Z6", "B00JHONN1S", "B008F0SU0Y", "B00D23MC6W", "B00AFDOPDA"],
"bought_together": ["D202BZX8Z6"]
},
"salesRank": {"Toys & Games": 211836},
"brand": "Coxlures",
"categories": [["Sports & Outdoors", "Other Sports", "Dance"]]
}
Here is my attempt (Please note, this is within a MapReduce program so some lines may seem out of context.):
JSONObject object = new JSONObject(sampleText); //sampleText is json that has been split by line
JSONArray boughtTogether = new JSONArray(object.getJSONArray("bought_together"));
using the following code, I hope it's help you.
//this will be your json object that contains and convert your string to jsonobject
//if you have json object already skip this.
JSONObject yourJSON = new JSONObject(targetString);
//getting the "related" jsonObject
JSONObject related = yourJSON.getJSONObject("related");
//getting the "bought_together" as an jsonArray and do what you want with it.
//you can act with jsonarray like an array
JSONArray bought_together = related.getJSONArray("bought_together");
//now if you run blow code
System.out.print(bought_together.getString(0));
//output is : D202BZX8Z6
-------update according to update the question------
you should change your code like this:
JSONObject object = new JSONObject(sampleText); //sampleText is json that has been split by line
JSONObject related = object.getJSONObject("related");
JSONArray boughtTogether = related.getJSONArray("bought_together");
-------update-------
i think you need to this point (it's not technicality all of they difference)
every thing are in {} , they will be JSONObject and the relation
is key and value like :
{"name":"ali"}
this is a jsonobject and the value of key "name" is ali and we call it
like:
myJsonObject.getString("name");
every thing are in [] ,they will be JSONArray and the relation is
index and value like :
["ali"]
this is a JsonArray the value of index 0 is ali and we call it
like:
myJsonArray.getString(0);
so in your case:
your total object is a JSONObject
the value of "related" key is still a JSONObject
the value of "bought_together" key (which is inside the value of {jsonobject} "related" key) is a JSONArray
I'm trying to parse this (for example) :
"id":"54f49b4a98686d9478ae44f5",
"title":"Free books",
"slug":"free-books",
"modules":[
[
"list",
{
"slug":"gutenberg",
"title":null,
"books":[]
}
]
]
}
How can i get the "books" array ? I use volley library.
Thanks
You can use JSONArray. Supposing you have a JSONObject called response you can get the books as following:
JSONArray modules = response.getJSONArray("modules");
JSONObject object = modules.getJSONObject(1);
JSONArray books = object.getJSONArray("book");
Take a look here in order to use it with Volley: http://www.androidhive.info/2014/09/android-json-parsing-using-volley/
I am having a converting that in to Json with following code
JSONObject jsonformatted = (JSONObject)JSONSerializer.toJSON(map);
FileWriter writer = new FileWriter("myfile.json");
It is working fine and out put is following
[ {"date":"July 4th", "event":"Independence Day"} ]
But I want the following format with a variable assign get value in Json
jsonstr = [ {"date":"July 4th", "event":"Independence Day"} ];
How can i add a variable to that
You can add a new data using put method in JSONObject
JSONObject jsonformatted = (JSONObject)JSONSerializer.toJSON(map);
jsonformatted .put("assign ", "some value")
Edit
OP wants to replace ':' with '='
Well you should not do it , because its the JSON standard.
Attributes and values are assigned using : and not by =
Check this link for more info
JSON wiki
I have an API Output like this:
{"user" : {"status" : {"stat1" : "54", "stats2" : "87"}}}
I create a simple JSONObject from this API with:
JSONObject json = getJSONfromURL(URL);
After this I can read the data for User like this:
String user = json.getString("user");
But how do I get the Data for stat1 and stat2?
JSONObject provides accessors for a number of different data types, including nested JSONObjects and JSONArrays, using JSONObject.getJSONObject(String), JSONObject.getJSONArray(String).
Given your JSON, you'd need to do something like this:
JSONObject json = getJSONfromURL(URL);
JSONObject user = json.getJSONObject("user");
JSONObject status = user.getJSONObject("status");
int stat1 = status.getInt("stat1");
Note the lack of error handling here: for instance the code assumes the existence of the nested members - you should check for null - and there's no Exception handling.
JSONObject mJsonObject = new JSONObject(response);
JSONObject userJObject = mJsonObject.getJSONObject("user");
JSONObject statusJObject = userJObject.getJSONObject("status");
String stat1 = statusJObject.getInt("stat1");
String stats2 = statusJObject.getInt("stats2");
from your response user and status is Object so for that use getJSONObject and stat1 and stats2 is status object key so for that use getInt() method for getting integer value and use getString() method for getting String value.
To access properties in an JSON you can parse the object using JSON.parse and then acceess the required property like:
var star1 = user.stat1;
Using Google Gson Library...
Google Gson is a simple Java-based library to serialize Java objects to JSON and vice versa. It is an open-source library developed by Google.
// Here I'm getting a status object inside a user object. Because We need two fields in user object itself.
JsonObject statusObject= tireJsonObject.getAsJsonObject("user").getAsJsonObject("status");
// Just checking whether status Object has stat1 or not And Also Handling NullPointerException.
String stat1= statusObject.has("stat1") && !statusObject.get("stat1").isJsonNull() ? statusObject.get("stat1").getAsString(): "";
//
String stat2= statusObject.has("stat2") && !statusObject.get("stat2").isJsonNull() ? statusObject.get("stat2").getAsString(): "";
If You have any doubts , Please let me know in comments ...