Cannot convert to JSONObject after updating array - android

I used to have a response string that I converted to JSONObject in this way:
JSONObject obj_temp = new JSONObject(response);
Then, I added to that string some modifications. At first, the index 'TripDetails' just had 1 trip with it details (trip information, passenger information and driver information). Now, with the new modifications, 'TripDetails' is an array of trips. Each index has the same information for each trip (trip information, passenger information and driver information). But now, with this new string, Android Studio gives me this error:
of type org.json.JSONArray cannot be converted to JSONObject
Can a string be casted to JSONObject if it has this format? It's a valid JSON string. Here's the complete JSON: https://paste2.org/VemkLNMJ

It is because you made your json object an array (I don't see why since you have just 1 element). Anyway you can probably do something like this:
JSONArray arr = new JSONArray(response);
JSONObject obj_temp = arr.getJSONObject(0);

your response starts with Array and you trying to convert it into Object.
[ represents json array node
{ represents json object node
JSONArray obj_temp = new JSONArray(response);
for(int i=0; i < jsonarray.length(); i++) {
JSONObject jsonobject = obj_temp.getJSONObject(i);
String id = jsonobject.getString("id");
String title = jsonobject.getString("title");
String company = jsonobject.getString("company");
String category = jsonobject.getString("category");}

Related

Parsing json code to a string in android using volley

i need help to parse this json code to actual strings using android volley. this is the json code:[{"name":"Tayo","0":"Tayo","thread_name":"Welcome","1":"Welcome","post":"Hi there,","2":"Hi there,","post_time":"Sunday","3":"Sunday"},{"name":"Pete","0":"Pete","thread_name":"Welcome","1":"Welcome","post":"Hi,am pete","2":"Hi,am pete","post_time":"Monday","3":"Monday"}].
I have tried other helps but not working. Thanks!
Remember:
if the .json content starts with { is considered as a Json Object.
if the .json content starts with [ is considered as a Json Array.
so you hava a JsonArray then you can parse your content like this way:
//Obtain the JsonArray
JSONArray jsonArray = new JSONArray(myJsonContent);
// Get the JsonObjects inside JsonArray
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonobject = jsonArray.getJSONObject(i);
}
// strData is the json data received.
JSONArray jsonArray = new JSONArray(strData);
for (int i=0; i<jsonArray.length();i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name = jsonObject.optString("name");
String zero = jsonObject.optString("0");
String thread_name = jsonObject.optString("thread_name");
String one = jsonObject.optString("1");
String post = jsonObject.optString("post");
String two = jsonObject.optString("2");
String post_time = jsonObject.optString("post_time");
String three = jsonObject.optString("3");
//Just an example
arrayName.add(jsonObject.optString("name"));
}
You can even use array to store data instead of the string.

How to parse JSON Array in android?

I have a JSON Array as follows:
jSONArray: {"li":[["apple\r\n","orange\r\n","mango\r\n"]]}
I want only the list as [apple, orange, mango] in android. Can anybody explain how to parse it in android without \r\n. I have tried as follows:
JSONArray jsonArray1 = new JSONArray(results.toString()); // which is the JSON Array
for(int i=0; i < jsonArray1.length(); i++) {
JSONObject jsonobject = new JSONObject();
JSONObject issue = jsonArray1.getJSONObject(i);
String _pubKey = issue.getString("li");
}
So, I am getting pubKey as [["apple\r\n","orange\r\n","mango\r\n"]]. I dont want \r\n.
Just replace those characters while parsing.
Example: If fruit is the string you want to put in your JSONArray jsonArray, call:
jsonArray.put(fruit.trim().replace("\r", "").replace("\n", ""));

Android JSONObject How get few JSONObject of one

I have JSONObject and I want get 8 object A,B,C...
my json string:
{"Matches":{"A":[{"team1":"Russia","team2":"France","time":"00:00:00","time0_90":"20","score":"0 : 0","stadium":"Maracana","referee":"ref","group":"A"},{"team1":"Portugal","team2":"Honduras","time":"00:00:00","time0_90":"60","score":"0 : 2","stadium":"","referee":"","group":"A"}]},"success":1}{"Matches":{"B":[{"team1":"Brazil","team2":"Spain","time":"00:00:00","time0_90":"3","score":"1 : 0","stadium":"","referee":"","group":"B"}]},"success":1}{"Matches":{"C":[]},"success":0}{"Matches":{"D":[]},"success":0}{"Matches":{"E":[]},"success":0}{"Matches":{"F":[]},"success":0}{"Matches":{"G":[]},"success":0}{"Matches":{"H":[]},"success":0}
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMathes = jsonResponse.optJSONArray("matches");
// ????????
Your response structure is:
JSONObject
key:value
JSONObject (key: "Matches")
JSONArray (key: "A")
JSONObject,
key:value,
key:value,
etc...
JSONObject
To get access to A, follow the steps below:
Create JSONObject from your response:
JSONObject jsonResponseObj = new JSONObject(jsonResponse);
Get JSONObject for the key "Matches"
JSONObject jsonMatches = jsonResponseObj.getJSONObject("Matches");
This object contains a JSONArray for the key "A", so let's get that array:
JSONArray jsonArrayA = jsonMatches.optJSONArray("A");
For your response, you have 2 JSONObjects in this array, so first, let's declare and initialize them:
//two JSONObjects
JSONObject[] jsonObjects = new JSONObject[jsonArrayA.length()];
//go through the array of JSONObjects and fetch them
for (int i=0; i < jsonObjects.length; i++) {
jsonObjects[i] = jsonArrayA.getJSONObject(i);
}
You now have A as JSONArray in jsonArrayA
A contains 2 JSONObjects, and you have them in jsonObjects[0] and josnObjects[1]
If you want to get the contents of those jsonObjects, simply fetch it using the keys, eg.:
String team1Obj1 = jsonObjects[0].getString("team1"); // will contain 'Russia'
String team2Obj2 = jsonObjects[1].getString("team2"); // will contain 'Honduras'
String stadium1 = jsonObjects[0].getString("stadium"); // will contain 'Maracana'
etc.

Android parsing a JSON message

I'm trying to parse the following JSON string
String _message = "GetXTRONResult: \"[{\"xtron\":\"Acub1\"},{\"xtron\":\"Acub2\"},{\"xtron\":\"Acub3A\"}]\"";
JSONObject jsonObj = new JSONObject(_message);
//Try to convert to array
JSONArray array = jsonObj.getJSONArray("GetXTRONResult"); //FAILS !
What is the best way to parse the above please?
UPDATE:
This is what the value is during debugging:
{"GetXTRONResult":"[{\"xtron\":\"Acub1\"},{\"xtron\":\"Acub2\"},{\"xtron\":\"Acub3A\"}]"}
org.json.JSONException: Value .... at GetXTRONResultof type java.lang.String cannot be converted to JSONArray
SOLUTION THAT WORKED FOR ME:
I had to use the iterator as follows:
ArrayList list = new ArrayList();
JSONObject jsonObj = new JSONObject(_message);
Iterator<?> keys = jsonObj.keys();
if (keys.hasNext()) {
JSONArray array = new JSONArray((String) jsonObj.get((String) keys.next()));
for (int i = 0; i < array.length(); ++i) {
list.add(array.getJSONObject(i).getString("xtron").toString());
}
You have some errors in your json string, like "[.
You can't use quotes that wrap your list.
This one should work:
String _message = "{\"GetXTRONResult\": [{\"xtron\":\"Acub1\"},{\"xtron\":\"Acub2\"},{\"xtron\":\"Acub3A\"}]}";
JSONObject jsonObj = new JSONObject(_message);
//Try to convert to array
JSONArray array = jsonObj.getJSONArray("GetXTRONResult");
System.out.println(array);
Output: [{"xtron":"Acub1"},{"xtron":"Acub2"},{"xtron":"Acub3A"}]
To avoid your confusion when making JSON in java/android
you could use single quote (') instead of double quote (") for JSON inside Java Code
For example:
from
"{\"xtron\":\"Acub1\"},{\"xtron\":\"Acub2\"},{\"xtron\":\"Acub3A\"}"
to be something like this
"{'xtron':'Acub1'},{'xtron':'Acub2'},{'xtron':'Acub3A'}"
I think this is what you're looking for:
JSONObject rootObj = new JSONObject(jsonString);
String theArrayJSON = rootObj.getJSONArray("GetXTRONResult");
JSONObject theArray = new JSONObject(theArrayJSON);

Simple Json parsing in android

I got the Json response. I am not able to get the values from the string.my string is
Json_response is
{"NameAllList":[{"Current":{"time":"2012-02-21T08:04:21","Name":"abcd"},
"Next":{"Name":"data1","StartTime":"2012-02-21T08:06:21"}},{"Current":{"time":"2012-02-21T08:14:21","Name":"defg"},
"Next":{"Name":"data2","StartTime":"2012-02-21T08:24:21"}},{"Current":{"time":"2012-02-21T08:28:21","Name":"ghij"},
"Next":{"Name":"data3","StartTime":"2012-02-21T08:34:21"}},{"Current":{"time":"2012-02-21T08:40:21","Name":"knmo"},
"Next":{"Name":"data4","StartTime":"2012-02-21T08:48:21"}}]}
and i tried this.
JSONObject jsonObj = new JSONObject(json_response);
JSONObject subObj = jsonObj.getJSONObject("Current");
String name_current =subObj.getString("Name");
but i am not able to get the value of "Name". what mistake i have done. provide the link to do the above parsing.
first of all, your JSON response is having NameAllList as a JSON Array of objects.
So you have to fetch JSON Array first, then you can fetch one-by-one object.
for example:
JSONObject jsonString = (new JSONObject(json_response_string));
JSONArray array = jsonString.getJSONArray("NameAllList");
for(int i=0; i<array.length(); i++)
{
// Retrieve Current object as such
JSONObject objCurrent = array.getJSONObject("Current");
// Retrieve Next object as such
JSONObject objNext = array.getJSONObject("Next");
}
You are not parsing json properly, so you are not able to fetch value of Name. Please note JSON Annotation [] represent JSONArray, and {} respresent JSONObject, so method to get current item's name is:
JSONObject jsonObj = new JSONObject(json_response_string);
JSONArray jsonArr=jsonObj.getJSONArray("NameAllList");
String Hora_name_current="";
for(int i=0;i<jsonArr.length();i++)
{
JSONObject obj=jsonArr.get(i);
try{
JSONObject subObj = obj.getJSONObject("Current");
Hora_name_current =subObj.getString("Name");
break;
}catch(JSONException ex)
{
}
}
looks like you're trying to use JSONObject when you should be using JSONArray for the second request. Try this:
JSONObject jsonString = (new JSONObject(json_response_string));
JSONArray array = jsonString.getJSONArray("NameAllList");
In your JSON return, "NameAllList is actually an array and needs to be handled as such. Once you set it to "array", you can then run a for loop and treat it like any other array in Java.
Let me know if that helps.
David
JSONObject jsonObj = new JSONObject(json_response_string);
JSONArray jsonArray = jsonObj.getJSONArrays("NameAllList");

Categories

Resources