3

I have a String. I am converting it to JSONOBJECT and I am trying to extract the values based on the key.

JSON STRING:

jsonString="
{
\"AREA\": [\"IT,SALES\"],
\"CITY\": [\"LA\",\"NORTH\"]
}";

I want the values of "AREA"in one string and CITY in one String. I have tried :

JSONObject jsonOb = new JSONObject("jsonString");
String area = jsonOb.getString("AREA");

But I am not able to retrieve the values in that way. Need some suggestions.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
user7637864
  • 237
  • 3
  • 5
  • 15

4 Answers4

3

You were trying to access Area directly whereas it is a JSONArray Object.

String json="{\"AREA\": [\"IT,SALES\"],\"CITY\": [\"LA\", \"NORTH\"]}";
JSONObject jsonOb = new JSONObject(json);
JSONArray arrJson=jsonOb.getJSONArray("AREA");

for(int i=0;i<arrJson.length();i++)
System.out.println(arrJson.getString(i));
Panda
  • 6,955
  • 6
  • 40
  • 55
Atul
  • 1,536
  • 3
  • 21
  • 37
2
JSONArray area = (JSONArray) jsonObject.get("AREA");
Iterator<String> iterator = area.iterator();
while (iterator.hasNext()) {
    System.out.println(iterator.next());
}

You should get a JSONArray object and then you can simply iterate and build the appropriate strings (using StringBuilder).

You can refer to this article for further help.

Alon Segal
  • 818
  • 9
  • 20
2

Your data has [], so use getJSONArray("AREA") and you can iterate over that.

(The method exactly would depend what library you have)

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
2

I believe this is what you are after:

    String jsonString = "{\"AREA\": [\"IT,SALES\"],\"CITY\": [\"LA\",\"NORTH\"]}";
    JSONObject jObj;
    String areaString = "";
    String cityString = "";
    try
    {
        jObj = new JSONObject(jsonString);
        areaString = jObj.getJSONArray("AREA").toString();
        cityString = jObj.getJSONArray("CITY").toString();
    }
    catch (JSONException e)
    {
        e.printStackTrace();
    }

    System.out.println("areaString: " + areaString);
    System.out.println("cityString: " + cityString);
dat3450
  • 954
  • 3
  • 13
  • 27