Domanda

After parsing JSON:

    JSONArray jsonArray = new JSONArray(ResponseString);
    for (int i = 0; i < jsonArray.length(); i++) {
       JSONObject currentObject = jsonArray.getJSONObject(i);
       String local_parameter = currentObject.getString("LOCAL_PARAMETER");
       }

I'm getting next string:

       {"Cost": 200,
        "Space": 33,
        "Accommodation": 1,
        "AirConditioning": 1,
        "Apartment": 1,
        "Campfire": 1,
        "Disability": 1,
        "Grill": 1,
        "Kitchen": 1,
        "Monument": 1,
        "Parking": 1,
        "Scene": 1,
        "Wifi": 1,
        "ClosedArea": 1 }

How to get ArrayList with key/values?

GOT SOLUTION: Just get currentObject as JSONObject and then get a string of value what you need:

 String cost = currentObject.getJSONObject("LOCAL_PARAMETER")
                            .getString("Cost").toString(); 
È stato utile?

Soluzione

Just parse the JSON object one more time for the value you need.

JSONArray jsonArray = new JSONArray(ResponseString);
for (int i = 0; i < jsonArray.length(); i++) {
   JSONObject currentObject = jsonArray.getJSONObject(i);
   String local_parameter = currentObject.getString("LOCAL_PARAMETER");
   String tmp = local_parameter.get("Cost").toString(); // this gets the value of Cost
   }

Altri suggerimenti

If you REALLY want to get an ArrayList containing your values, you can do it like this, even if I don't think this way to use JSONObjects is the best one :

final ArrayList<Pair<String, Integer>> values = new ArrayList<Pair<String,Integer>>();
final JSONObject localParams = new JSONObject(local_parameter);
final Iterator<String> iterator = localParams.keys();
while (iterator.hasNext())
{
    final String key = iterator.next();
    values.add(new Pair<String, Integer>(key, localParams.optInt(key)));
}

But I REALLY don't think this is the best way to handle JSONObjects...

Create an model class with the key of the json and parse it to the model class using gson.

A a = gson.fromJson(jsonRes.toString(),A.class);
here A is your model class and a is the instance of A
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top