0

I have the following string, which was created using javascript JSON. (It's passed from a Webview to the native code using JavascriptInterface.)

{"var1":1,"var2":8}

How do I convert that into an object and then iterate over the key/value pairs? The names of the keys are NOT known in advance.

I have seen this JSON Array iteration in Android/Java and this Converting json string to java object? and this how to convert JSON string to object in JAVA android.

None of those seem to fit with my example, which is a dictionary with unknown key names. At least, it's certainly not clear to me which of the 15+ answers is relevant for my case.

user984003
  • 28,050
  • 64
  • 189
  • 285

2 Answers2

1

The org.json library comes "for free" with Android, so I'd go with that. Usage when you don't know the keys ahead of time could be something like this:

try {
    JSONObject jsonObject = new JSONObject(/* your json String here */);
    Iterator<String> keys = jsonObject.keys();

    while (keys.hasNext()) {
        String key = keys.next();
        String value = jsonObject.getString(key);

        // do whatever you want with key/value
    }
}
catch (JSONException e) {
    // thrown when:
    // - the json string is malformed (can't be parsed)
    // - there's no value for a requested key
    // - the value for the requested key can't be coerced to String
}
Ben P.
  • 52,661
  • 6
  • 95
  • 123
0

You can use it by converting the getting the json length like this:- JSONObject obj = new JSONObject(response);

    for (int i = 0; i < obj.length(); i++) {
    //getting the json object of the particular index inside the array
     JSONObject heroObject = obj.getJSONObject(i);
     String aka=heroObject.getString("your key here");
}
Lutaaya Huzaifah Idris
  • 3,596
  • 8
  • 38
  • 77
  • Then how do I get the key/value pairs once I have that object? – user984003 Jan 22 '18 at 19:17
  • you can store them in a String like this:- String aka=heroObject.getString("your key here"); –  Jan 22 '18 at 19:19
  • I don't know the names of the keys in advance. I need to iterate over the object and extract all the keys and values. – user984003 Jan 22 '18 at 19:20
  • ok so you can firstly store the length of the JSON object and declare an public empty string like String s=""; then do like this: - for(int i=0;i –  Jan 22 '18 at 19:22