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 ?

2
  • 1
    the problem with your code, is that keys() returns also data as key Commented Dec 30, 2014 at 14:15
  • @Blackbelt I had a problem on my question, I update my new json data , Could you check it out ? Commented Dec 30, 2014 at 15:48

3 Answers 3

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");
Sign up to request clarification or add additional context in comments.

1 Comment

I had a problem on my question, I update my new json data , Could you check it out ?
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.

Comments

1

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

1 Comment

I had a problem on my question, I update my new json data , Could you check it out ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.