I have tried several of the examples listed and none of them seem to work for some reason so I am posting a new question.
I have a JSON string coming to me however it is all objects (it is not formatted in an array). I need to parse out the Team names from this. I know I need to iterate over them as they are the keys and then store the objects in a new array.
Here is the JSON (a sample of it)
{"query":{"printrequests":[{"label":"","typeid":"_wpg","mode":2,"format":false}],"results":{"Team:Kubbchucks":{"printouts":[],"fulltext":"Team:Kubbchucks","fullurl":"http://wiki.planetkubb.com/wiki/Team:Kubbchucks","namespace":822,"exists":true},"Team:Kubbchucks
IDP":{"printouts":[],"fulltext":"Team:Kubbchucks
IDP","fullurl":"http://wiki.planetkubb.com/wiki/Team:Kubbchucks_IDP","namespace":822,"exists":true}},"serializer":"SMW\Serializers\QueryResultSerializer","version":0.5,"meta":{"hash":"8407a177d701d746edc3066a012c17d2","count":2,"offset":0}}}
What I have so far to dig down to that level of the JSON (data is the string above)
JSONObject parsing = new JSONObject(data);
JSONObject query = parsing.getJSONObject("query");
JSONObject results = query.getJSONObject("results");
This allows me to manually check for a team using :
JSONObject teamone = results.getJSONObject("Team:Kubbchucks");
This is of course not ideal. The full JSON file has almost 3000 entries and I do not know what those entries all are. I need to iterate over the results object to get the keys that start with "Team:"
I've tried a few different iterator samples but none seem to be working for me and it is starting to really frustrate me. Believe me, I've tried many things before asking the question. Any help is appreciated.
I had a similar problem some time ago.
You can do like this:
JSONObject results = query.getJSONObject("results");
Iterator<String> iterator = results.keys();
while (iterator.hasNext()) {
JSONObject team = results.getJSONObject(iterator.next());
// do stuff
}
Related
Here's my JSON data sample:
{
"node_1.1":{
"someCrap":{
"someCrap":"SomeValue"
}
},
"node_1.2":{
"Node_1.2.1":{
"Node_1.2.1.1":{
"param1":value,
"param2":value,
"param3":"value",
"paramThatIneed":{
"ThisIsWhatIActuallyNeed":"url",
"width":96,
"height":72
}
},
"Node_1.2.1.2":{
Same as above, just that paramThatINeed might be missing, gotta place imagePlaceHolder Here
},
//and so on... there are a total of 50 of these..
}
}
}
Now I could get the node_1.1 and Node 1.2 and the sub-node of it node_1.2.1
However, there are 50 sub-nodes inside of node_1.2.1, and they will have random names returned from the server. Its in string format but they're actually ints. Its a page ID.
Now I wanna iterate through the node_1.2.1 and get those sub-nodes and access their sub-nodes and take in the URL of the paramThatINeed. If the paramThatINeed is not present, I need to put some null/dummy value.
This is the code that I tried to work it as far as I've reached:
JSONObject jsonObj = new JSONObject(jsonStr); //jsonStr is the entire JSON string
JsonObject node_1.2= jsonObj.getJsonObject("node_1.1");
JsonObject node_1.2.1 = node_1.2.getJsonObject("node_1.2.1");
What do I do after this? Because I can only getJsonObject by passing a string param to it, I tried using the for loop but it doesn't take any int param.
Also, as I said before, the nodes after that have random names and not fixed. So I'm totally confused.
Please help me out if you know how to solve this problem. Please remember there's no JsonArray in this. I'm probably thinking of editing the JSON string itself and replacing some parts of the '{' with '[' and converting it to an array :( ... I think that's a sad approach.
Use this to iterate over an object.
Android (JSONObject) How can I loop through a flat JSON object to get each key and each value
but be careful, from json object you won't get the result in original order, like in json array. The result will be in alphabetical order (I hope I was clear). And you can use optJsonobject(), instead of getJsonObject(). It will returns null, instead of throw exception. You can use opt every where instead of get.
I know how to get jsonarray from jsonobject. I am doing like below code to get jsonarray.
JSONObject recvJson = new JSONObject(holder.toString());
String numberByte= (String) recvJson.get("data");
String ts = (String) recvJson.get("time");
JSONObject temp2 = new JSONObject("{ \"data\" : " + numberByte+ "}");
JSONArray recvJarray = temp2.getJSONArray("data");
for (int i = 0; i < recvJarray.length(); i++)
{
byteArray[i] = (byte) recvJarray.getInt(i);
}
But don't want to use for-loop, without using for-loop or any other loop want to retrieve jsonarray data values.
How should I do ?? I have done google & saw many forums but dint succeed to retrieve data without using for-loop.
for example : I ll be getting 80 - 100 packets of 1024bytes per second from server, I want to retrieve this data & store it into bytearray. By usingf for-loop its taking around 300ms- 400ms and I am loosing many packets between that. So I want to use different approach. If any Idea or solution for cracking this.
Help will be appreciated !!
You can use GSON to parse the json objects. It is much faster and easier to decode json data.
Check these links.
Gson1, Gson2
try usig gson
it uses java reflection to convert objects to json and json to object with simple methods
toJson(),fromJson() (and it works for object arrays and lists too)
but you have to write the proper classes for the jsons (with all fields)
read the documentation.
A PHP script is sending to an Android app some data in the following format
[{"event_id":"4","message":"test"},["person1","person2"]]
I want to exact the 2 elements from this array into other arrays so I can easily manipulate the data. I got to the point in which the above response from the server is being converted into as string. What I can't seem to be able to do is to parse the data into arrays. I'm trying something on the following lines:
receivedData = new JSONArray(result); //result is the string response from the server
JSONArray array1= receivedData.getJSONArray(0);
JSONArray array2= receivedData.getJSONArray(1);
int len = array1.length();
but lenis not giving me back anything :(
What am I doing wrong and how could I change it.
Many thanks
What if you start by invoking new JSONObject(result); and then pulling an array out of that? I suspect you're trying to pull an array out of something that is not an array. Your PHP should not return something wrapped in [ ] it should return it wrapped in { }... also I believe your third JSON element (the array itself) is just hanging about without a label, which I believe is illegal.
so...
if your php produced this:
{"event_id":"4","message":"test"},"people": ["person1","person2"]}
and your java was this:
JSONObject j = new JSONObject(result);
String [] people = j.getJSONArray("people");
I believe you'd have what you are after.
I have a question that I am a little bit confused about. I am quite new to JSON and getting JSON values in the android API. I am trying to access an array within the response I get. the JSON code I am getting is something like this:
Response:
{
"event": {
"participants": []
},
"status": "success"
}
How would I access the participants array and store their values. This is what I am trying at the moment... but I dont appear to be getting what I want.
try{
//get the JSON values from the URL.
JSONObject json = jParser.getJSONFromUrl("http://somesite.com/api/find?"+"somevar="+someJavaStringVar);
json_event = json.getJSONObject("event");
JSONArray json_array_participants = json_event.getJSONArray("participants");
} catch(JSONException e) {
}
The thing I am mostly confused about is... what is the arrays type equivalent to. Any advice or reasoning as to the correct way to get ahold of that variables value would be great... thanks guys.. :).
Think JSON is really just a key-value pairing. The JSONArray type is just an array full of objects (like Object[]) - it has no idea what the objects it contains are or what they're to be used for. Its up to you to assign meaning to the JSON stream based on what you know of the source. From what I see of your code, most of it looks fine, though I don't know what your jParser.getJSONFromURL() is doing. Typically, you would build the JSON from the response string like so:
String jsonString = getJSONFromUrl("http://somesite.com/api/find?"+"somevar="+someJavaStringVar);
JSONObject json = new JSONObject(jsonString)
JSONObject json_event = json.getJSONObject("event");
JSONArray json_array_participants = json_event.getJSONArray("participants");
You can iterate through the array like any other array to get subobjects or whatever:
for(int i=0; i < json_array_participants.getLength(); i++) {
JSONObject participant = json_array_participants.getJSONObject(i);
// Do stuff
}
As a side note - I WOULDN'T use GSON until you understand the underlying protocol, at least a little - because you never know when you might want to parse your JSON from a different language for some reason.
I would strongly recommend to use gson instead as your preferred parser since it will do all the job of serializing and deserializing for you except creating the domain objects.
This tutorial should get you going:
http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html
This will depend on what the server is supposed to return. It could be an array of anything and if this is a public service, there should be a specification to go off of.
If you are in charge of the server portion as well, and you have a backing object, Google's GSON library is extremely easy to use. It will also keep type information straight.
noob Android/JSON person here. I hope someone might help me?
I've looked and looked but don't think it's what I'm after. I've been working on this project all day so maybe my brain has just gone to mush... If this has been awnsered else where please point me that way :)
Anyway, I wish to get a specific object from within an JSONArray - here's what's happening so far:
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_obj = jArray.getJSONObject(i);
name = json_obj.getString("txt_title");
}
txt_title.setText(name);
As far as I understand result returns the entire JSONArray, then I go through the length of those results using the for loop and get the json objects. At the moment I'm only asking for values from "txt_title" in the Array. So far, so good?
Then what I want to do is, say only set the third "txt_title" value from the Array.
At the moment I would expect txt_title.setText(name) to be displaying ALL the titles in "txt_title" however it's only displaying the LAST title in the Array. This probably has something to do with the for loop?
How would I go about choosing which object is displayed?
You are only displaying the last one in the list right now because you are setting name each time in the loop.
name = json_obj.getString("txt_title");
this overwrites the previous value every time you iterate. If you want to have all the values, you would have to do it in an additive way.
name += json_obj.getString("txt_title");
If you want to get a specific item from the array you just need to access it using the index you want instead of a loop.
if(jArray.length() > 2) {
JSONObject json_obj = jArray.getJSONObject(2); //get the 3rd item
name = json_obj.getString("txt_title");
}
Hope that helps you understand how to access it.
If you can ensure that the element will exist at the index you can skip the loop entirely.
JSONArray jArray = new JSONArray(result);
String name = jArray.getJSONObject(2).getString("txt_title");
txt_title.setText(name);