0

this is my json string for example :

{"data":{ "name":"Red Sox win 7-0!","famil":"INSERT TITLE HERE","tel":"2251472"}}

this is the code I write but it couldn't get the values:

        JSONObject jsons = new JSONObject(myString);
        Iterator<?> keys = jsons.keys();
        String out = "";
        while (keys.hasNext()) {
            String key = (String) keys.next();
            out += key + ": " + jsons.getString(key) + "\n";
        }

How can I get each item's value ?

mahdi yamani
  • 923
  • 3
  • 12
  • 29

3 Answers3

2

try this code.

    JSONObject object = new JSONObject(myString);

    JSONObject objectData = object.getJSONObject("data");

    String strTel = objectData .optString("tel");
    String strFamil = objectData .optString("famil");
    String strName = objectData .optString("name");
Rakesh Rangani
  • 1,039
  • 10
  • 13
1

In your case you can use jsons.getString(key) for each key because your JSONObject contains only Strings.

But in general, JSONObject can contain values of different types: integer, boolean, int/long, double JSONArray and JSONObject. You have to use the right .getSomething() for each one or generat .get() that retuns Object.

atok
  • 5,880
  • 3
  • 33
  • 62
1

Great example json-simple-example-read-and-write-json

Filip
  • 2,244
  • 2
  • 21
  • 34