0

I'm trying to write a cordova plugin. I've the following JSON data:

JSONObject obj = {"amount":100, "desc":"blabla",id:123}

and I'm trying to iterate the JSON keys and put keys and values to intent.putExtra(key,val)

Example:

Iterator<String> iter = obj.keys();
while (iter.hasNext()) {
    key = iter.next();
    value = obj.getString(key);
    intent.putExtra(key, value);
}

With this code I get the error

error: cannot find symbol intent.putExtra(key, value);

Anyone can say me how correct iterate JSON data and execute putExtra()?

try-catch-finally
  • 7,436
  • 6
  • 46
  • 67
soSlow
  • 9
  • 2

2 Answers2

0

First, the json you provide is not valid. It should be something like:

{"amount":100, "desc":"blabla","id":123}

Then, as said in the comments, create an intent variable outside the for loop. And finally, you should use

Object value = obj.get(key)

because values can be Strings or Integers.

Lino
  • 5,084
  • 3
  • 21
  • 39
0

Extension to Lino's answer.

As Intent.putExtra(String, Object) is not available, you need following modifications.

        JSONObject obj = new JSONObject("{" +
                "\"amount\": 100," +
                "\"desc\": \"blabla\"," +
                "\"id\": 123," +
                "\"id2\": 123.56" +
                "}");

        Intent intent = new Intent();
        Iterator<String> iter = obj.keys();
        while (iter.hasNext()) {
            String key = iter.next();
            Object value = obj.get(key);
            if (value instanceof Float || value instanceof Double) {
                intent.putExtra(key, (double) value);
            } else if (value instanceof Integer || value instanceof Long) {
                intent.putExtra(key, (long) value);
            } else if (value instanceof String) {
                intent.putExtra(key, (String) value);
            } /*else if (more cases go here) {

            } */
        }
user3161880
  • 1,037
  • 6
  • 13