How to decode an array of array elements in Android - android

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.

Related

Android JSON fetching - No value for (value) eventhough the value exists

I have a valid json link, and I want to fetch data from it.
This is my code, for fetching data:
try {
JSONObject topicsObject = new JSONObject(getTopicsJSON);
JSONArray topics = topicsObject.getJSONArray("Topics");
for (int i = 0; i<topics.length();i++){
SuperTrenerTopic stt = new SuperTrenerTopic();
JSONObject sub_topic = topics.getJSONObject(i);
JSONObject topic = sub_topic.getJSONObject("Topic");
...
}
On the last line of code, I get ann error saying org.json.JSONException: No value for Topic.
Following screenshot shows that it is not correct, as I Log-ed the recieved JSON, and you can clearly see that in fact, there IS a "Topic" object out there:
First Log represents the first part of an entire Json responce, and the second one is the Topic object itself.
Here is another screenshot of the JSON format i took from my browser:
You can notice that "Topic" and "meta" objects are on the same hierarchy level.
I fetch "meta" object with no problem whatsoever, using the same code I would use for fetching 'Topics", but for some reason, fetching "Topics" doesn't work out.
here is the code I successfully use to fetch "meta' object:
JSONObject meta = sub_topic.getJSONObject("meta");
What could be the cause of this?
Is there something realy obvious that I'm missing out?

Iterating through JsonObject in Java/Android. NOT JsonArray

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.

JSON Array or Object Error in Android

I have a string being returned from a HttpClient called data.
Data = {"result":[{"id":"2","contextID":"1","name":"Kitchen","image":"81"},
{"id":"1","contextID":"1","name":"Living Room","image":"18"},
{"id":"3","contextID":"1","name":"Toilet","image":"75"}]}
I am then performing this code:
resultArray = new JSONArray (data);
and returning this JSONArray. However, I get a JSONException error:
JSONObject cannot be converted to JSONArray
Surely this is a JSONArray not a JSONObject? Or is it a JSONObject of JSONObjects? I'm pretty new to JSON and I'm wanting to loop through and create new Locations using these imported values. Is there an easy or established way of doing this?
Many Thanks.
Data is a JSONObject, and Data["result"] is a JSONArray that contains JSONObjects.
Its a json object with a JSONArray of JSONObjects inside of it. { } means object and [] means array. So you get the top level string as a JSON object, then get the results parameter as an array, then get each index into the results as an object (and you can get the parameters of those via getString, etc).
Data is actually a JSONObject that contains a JSONArray named "result." If you wanted to get the JSONArray you'd have to do the following:
JSONObject dataObj = new JSONObject(data);
JSONArray dataArr = dataObj.getJSONArray("result");
For future reference, since you're new to JSON, data inside {} braces is a JSONObject and data inside [] braces is a JSONArray. Arrays and objects can be nested inside of each other and it's sometimes hard to read. I recommend formatting your data if you need help reading it. I personally use http://jsonformatter.curiousconcept.com/ to format and validate my data. I'm not associated with the site in any way. I just find it really useful.

Android : how to get jsonarray from json object in different ways

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.

Accessing an object from JSON in Android

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.

Categories

Resources