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
  • 704,970
  • 168
  • 1,303
  • 1,425
user7637864
  • 229
  • 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,940
  • 6
  • 37
  • 53
Atul
  • 1,490
  • 3
  • 20
  • 35
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
  • 798
  • 7
  • 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
  • 151,199
  • 17
  • 111
  • 216
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
  • 12
  • 27