-3

When send email parameters to server and the response is shown as a string below.

[
{
    "nid": "478",
    "field_mc_bacheliers_value": "0",
    "field_mc_defi_collectif_value": "1"
},
{
    "nid": "480",
    "field_mc_bacheliers_value": "0",
    "field_mc_defi_collectif_value": "1"    
}
]

I want to read this response String format into jsonobject. I it is the first time i work with json.

Raghunandan
  • 132,755
  • 26
  • 225
  • 256
Dimitri
  • 677
  • 3
  • 19
  • 46

4 Answers4

5

Considering the below extra curly brace removed }

[
{
    "nid": "478",
    "field_mc_bacheliers_value": "0",
    "field_mc_defi_collectif_value": "1"
},
{
    "nid": "480",
    "field_mc_bacheliers_value": "0",
    "field_mc_defi_collectif_value": "1"
}
]

To parse

  JSONArray myListsAll= new JSONArray(myjsonstring);
  for(int i=0;i<myListsAll.length();i++){
  JSONObject jsonobject= (JSONObject) myListsAll.get(i);
  String id=jsonobject.optString("nid");
  String value1=jsonobject.optString("field_mc_bacheliers_value");
  String value2=jsonobject.optString("field_mc_defi_collectif_value");  
  System.out.println("nid="+id);
  System.out.println("value1="+value1);
  System.out.println("value2="+value2); 
  }

Output

nid=478
value1=0
value2=1
nid=480
value1=0
value2=1
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
3

Remove this extra curly braces '}'

You can refer below code For the json

[ 
{
  "name" : "Test",
  "id" : 512
}, {
  "name" : "Test2",
  "id" : 573
}, {
  "name" : "Test3",
  "id" : 585
}
]

Parse Like this

ArrayList<String> arrProducts = new ArrayList<String>();

try {
    JSONArray valarray = new JSONArray(jsonstring);
    for (int i = 0; i < valarray.length(); i++) {

        String str = valarray.getJSONObject(i).getString("name");
        arrProducts.add(str);
    }
} catch (JSONException e) {
    Log.e("JSON", "There was an error parsing the JSON", e);
}
Nirali
  • 13,571
  • 6
  • 40
  • 53
1

Try this

jString=[{"nid":"478","field_mc_bacheliers_value":"0","field_mc_defi_collectif_value":"1"},{"nid":"480","field_mc_bacheliers_value":"0","field_mc_defi_collectif_value":"1"}}]
    jObject = new JSONObject(jString);
   String id = jObject .getString("id");

Hope it helps

Benil Mathew
  • 1,638
  • 11
  • 23
0

It is not valid JSON, you have an extra } at the end.

[
  {
    "nid": "478",
    "field_mc_bacheliers_value": "0",
    "field_mc_defi_collectif_value": "1"
  },
  {
    "nid": "480",
    "field_mc_bacheliers_value": "0",
    "field_mc_defi_collectif_value": "1"
  }
} <-- this is invalid
]

You can check that here: http://jsonviewer.stack.hu/

This question has more hints for JSON parsing: How to parse JSON in Android

Community
  • 1
  • 1
dannrob
  • 1,061
  • 9
  • 10