I have a JSONObject with multiple JSONArrays in it. I have written a for loop to loop through the object but i need to get the JSONArray at the Index position. Does anyone know how to do this?
heres my JSONObject
{"Contacts": //JSONObject
{
"B"://JSONArray..
[
{"ContactName":sdfsdf,"ID":900,"Number":1368349},
{"ContactName":adsdfd,"ID":1900,"Number":136856},
{"ContactName":adglkhdofg,"ID":600,"Number":136845}
],
"C":[
{"ContactName":alkghoi,"ID":900,"Number":1368349},
{"ContactName":wetete,"ID":1900,"Number":136856},
{"ContactName":dfhtfh,"ID":600,"Number":136845}
]
.....//and so on..
}
}
heres my for loop this issue i'm having is that to retrieve a JSONArray from a JSONObject it requires a string but i'm trying to get the Array at object Index in the JSONObject
JSONArray headerStrings = contacts.names();
Log.v("Main", "headerStrings = " + headerStrings);
SeparatedListAdapter adapter = new SeparatedListAdapter(this);
for (int t=0; t<contacts.length(); t++){
adapter.addSection(headerStrings.getString(t), new DocumentArrayAdapter (getActivity(),R.layout.document_cell,contacts.getJSONArray(t););
}
Try this:
for (Iterator it = contacts.keys(); it.hasNext(); ) {
String name = (String)it.next();
JSONArray arr = contacts.optJSONArray(name);
// now add this to your adapter
}
Note, that the order of the elements of a JSONObject is not defined.
Here, You will get matched index.
int matchedIndex =0;
for(int i=0;i<jsonArray.length();i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
if( 123 == jsonObject.getInt("Id")){
matchedIndex = i;
//jsonArraySelectedBikes.remove(matchedIndex);
break;
}
}
Related
I have a response from the server like this:
[
"test1",
[
"test2",
"test3",
"test4"
]
]
I try to parse this response to JSONObject but when log jsonObject.toString(), It doesn't show anything. So I just parse response with JSONArray and want to show in RecyclerView:
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
DataModel dataModel = new DataModel();
dataModel.setId(i);
dataModel.setWord(jsonArray[i]);
temp.add(dataModel);
}
but I have error on jsonArray[i]. I can from the beginning, Do like this:
JSONArray jsonArray = new JSONArray(response);
response = jsonArray.toString().replaceAll(" []" ", "");
String[] words = response.split(",");
And with a for loop, Added data to RecyclerView. But if a word in response contain {"}, this way remove it.
How pare this json?
You have to check for each element whether it is an array or a String and parse it dynamically.
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
//here check if jsonArray[i] is String or not
//if its an array then do
// JSONArray jsonArray2 = new JSONArray(jsonArray[i]);
}
Though the JSON is valid, it has a weird structure. I am not sure if you can fit this JSON in a consistent data model.
Looks like the first element is a String and the second element is another list. Hence you could do something as follows.
List<String> allElements = new ArrayList<>();
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
try {
// Try to parse it to an array
JSONArray elementArr = new JSONArray(jsonArray[i]);
for (int j = 0; j < elementArr.length(); j++) {
// I hope the nested JSON array is not messed up!!
allElements.add(elementArr[j]);
}
} catch (Exception e) {
// The element is not an array, hence add it to the list directly
allElements.add(jsonArray[i]);
}
}
Finally, allElements should have all the strings that you want.
I have json data as mentioned below.
{
"data":[
{
"Products":{
"id":"86",
"pname":"mi4",
"pcat":"9",
"subcat":"8",
"seccat":"0",
"oproduct":"1",
"pdetails":"Good phone",
"pprice":"10000",
"pdiscount":"10",
"qty":"1",
"qtytype":"GM",
"dcharge":"40",
"pimage":null,
"sname":"Easydeal",
"sid":"1100",
"size":"",
"pincode":""
}
}
]
}
I can identify array as getJSONArray("datas"). But I want to get pname and sname values.
Just reach the object
JSONObject resp=new JSONObject("response");
JSONArray data=resp.getJSONArray("data");
now if you want to get object at a particular index(say '0')
JSONObject objAt0=data.getJSONObject(0);
JSONObject products=objAt0.getJSONObject("products");
String pName=products.getString("pname");
you can similarly traverse the array
for(int i=0;i<data.lenght();i++){
JSONObject objAtI=data.getJSONObject(i);
JSONObject products=objAtI.getJSONObject("products");
String pName=products.getString("pname");
}
To get the to the key "Products" you should do:
JSONObject productsObject = YOUROBJECTNAME.getJSONArray("data").getJSONObject(0).getJSONObject("Products");
Then to get the values in productsObject you should do:
productsObject.getString("id");
productsObject.getString("pdetails");
And so on.
Try out the following code:
JSONObject object = new JSONObject(result);
JSONArray array = object.getJSONArray("data");
JSONObject object1 = array.getJSONObject(0);
JSONObject products = object1.getJSONObject("Products");
int id = object1.getInt("id");
String pname = object1.getString("pname");
This is how you get pname and sname:
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray;
try {
jsonArray = jsonObject.getJSONArray("data");
for(int counter = 0; counter <jsonArray.length(); counter++){
JSONObject jsonObject1 = jsonArray.getJSONObject(counter);
JSONObject products = jsonObject1.getJSONObject("Products");
String pname = products.getString("pname");
String sname = products.getString("sname");
}
} catch (JSONException e) {
e.printStackTrace();
}
PS: Poor JSON structure :)
I am working in Android and finding json from internet that looks like this:
JSONObject childObject=me.getJSONObject(pos);
String fisrtkey=childObject.getString("A");
JSONArray jsonArray=childObject.getJSONArray("c");
I want to find C21 that is in the A. See the json coming from request.
Can someone help me?
try {
JSONObject j=new JSONObject(data);
JSONArray c= null;
c = j.getJSONArray("This");
JSONObject item=c.getJSONObject(0);
JSONArray me=item.getJSONArray("me");
for(int pos=0;pos<me.length();pos++)
{
JSONObject childObject=me.getJSONObject(pos);
String fisrtkey=childObject.getString("A");
JSONArray jsonArray=childObject.getJSONArray("c");
}
} catch (JSONException e1) {
e1.printStackTrace();
}
//hope this will help you and also check json is invalid or not ,you missed
// bracket of jsonarray "me".
You have missed THIS json array while parsing. First get that and from that json object and then get ME json array. Something like this
JSONObject j = new JSONObject(data);
JSONArray c = j.getJSONArray("This");
JSONObject j1 = c.getJSONArray(0);
JSONArray d = j.getJSONArray("me");
for(int n = 0; n < c.length(); n++) {
JSONObject item = c.getJSONObject(n);
System.out.println(item.getString("A"));
}
Try this:
JSONObject j = new JSONObject(data);
JSONArray c = j.getJSONArray("me");
for(int n = 0; n < c.length(); n++) {
JSONObject person = (JSONObject) c.get(n );
String id = person.getString("A");
...
}
The is my JSON string .
{
"server_response":
{
"source_response" :
[
{"stoppage_name":"sealdah","bus_no":"43#230#234/1#30_A"}
] ,
"destination_response" :
[
{"stoppage_name":"howrah","bus_no":"43#234/1#30_A"}
]
}
}
I think there would be a '[' after "server_response" , but not sure .
I am trying to retrieve the data but the code is not working .
try {
jsonObject = new JSONObject(json_string);
jsonArray = jsonObject.getJSONArray("server_response");
int count=0 ;
String stoppage,busno;
while(count<1)
{
JSONArray JA = jsonArray.getJSONArray(0);
JSONObject JO = JA.getJSONObject(count);
stoppage = JO.getString("stoppage_name");
busno = JO.getString("bus_no");
Toast.makeText(getApplicationContext(),"Stoppage ="+ stoppage+" Bus no =" +busno, Toast.LENGTH_LONG).show();
count ++;
}
} catch (JSONException e) {
e.printStackTrace();
}
Where I am making wrong . I am new to JSON and Android.
jsonObject = new JSONObject(json_string);
jsonServerObject = jsonObject.getJSONObject("server_response");
jsonSourceArray = jsonServerObject.getJSONArray("source_response");
jsonDestinationArray = jsonServerObject.getJSONArray("destination_response");
//Iterate your 2 arrays
server_response is not a JSONArray, it's a JSONObject. Because array have numeric key, not string.
i have already answer this type of question .. what you have to do .. use multiple for loop to getting value inside array under array.
this is srceen shots
JSONArray objJson = new JSONArray(strJSONData);
System.out.println("AppUserLogin:"+objJson);
// Parsing json
if(arrJson.length()>0)
{
for (int i = 0; i < objJson.length(); i++) {
try {
JSONObject objprod = arrJson.getJSONObject(i);
HashMap<String, String> MaplistTemp = new HashMap<String, String>();
MaplistTemp.put("replyCode",
objprod.getString("replyCode"));
MaplistTemp.put("replyCode",
objprod.getString("replyCode"));
JSONArray objproduct_var = new JSONArray(objprod.getString("LearningStandards"));
if ((objproduct_var.length()) > 0) {
for (int k = 0; k < objproduct_var.length(); k++) {
JSONObject objprodvar = objproduct_var
.getJSONObject(k);
MaplistTemp
.put("1",
objprodvar
.getString("1"));
MaplistTemp
.put("2",
objprodvar
.getString("2"));
MaplistTemp
.put("3",
objprodvar
.getString("3"));
MaplistTemp
.put("4",
objprodvar
.getString("4"));
}
}
// sub_categorys_details.add(sub_cat_det);
medpostList.add(MaplistTemp);// adding to final hashmap
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Try this , and {} = object [] = array
try{
jsonObject = new JSONObject(json_string);
injsonObject = jsonObject.getJSONObject("server_response");
jsonArray = injsonObject.getJSONArray("source_reponse");
}catch(Exception e){}
sonArray = jsonObject.getJSONArray("server_response");
Here you are trying to access server_response as an array. It isn't an array. "server_response" is the key to the nested object:
{
"source_response" :
[
{"stoppage_name":"sealdah","bus_no":"43#230#234/1#30_A"}
] ,
"destination_response" :
[
{"stoppage_name":"howrah","bus_no":"43#234/1#30_A"}
]
}
See? Thats not an array, tis a JSON object with two keys, each of them have an array as value.
I'm not very familiar with android or java but in plain old javascript you could try something like:
var sourceResp = jsonObject.server_response.source_response;
or
var sourceResp = jsonObject["server_response"]["source_response"];
That will produce an array with one item in it.
I hope this can get you going.
Hi I'm trying to sort a JSONArray of JSONObjects alphabetically but it seems to add in backslashes as it turns it into one big string. Does anyone know how to do arrange a JSONArray of JSONObjects Alphabetically?
I have tried converting the JSONArray to arraylist but it becomes an JSONArray of Strings that are in alphabetical order rather than JSONObjects
public static JSONArray sortJSONArrayAlphabetically(JSONArray jArray) throws JSONException{
ArrayList<String> arrayForSorting = new ArrayList<String>();
if (jArray != null) {
for (int i=0;i<jArray.length();i++){
//FIND OUT COUNT OF JARRAY
arrayForSorting.add(jArray.get(i).toString());
}
Collections.sort(arrayForSorting);
jArray = new JSONArray(arrayForSorting);
}
return jArray;
}
Maybe something like this?
public static JSONArray sortJSONArrayAlphabetically(JSONArray jArray) throws JSONException
{
if (jArray != null) {
// Sort:
ArrayList<String> arrayForSorting = new ArrayList<String>();
for (int i = 0; i < jArray.length(); i++) {
arrayForSorting.add(jArray.get(i).toString());
}
Collections.sort(arrayForSorting);
// Prepare and send result:
JSONArray resultArray = new JSONArray();
for (int i = 0; i < arrayForSorting.length(); i++) {
resultArray.put(new JSONObject(arrayForSorting.get(i)));
}
return resultArray;
}
return null; // Return error.
}
The function's caller can free the JSONArray and JSONObject elements when he no longer needs them.
Also, if you just want to sort a JSONArray, you can look here:
Sort JSON alphabetically
and eventually here:
Simple function to sort an array of objects