0

I want to parse json from a url and use the json data with a listview. I also want to only list the score and the name, but I have no idea how. Thanks.

{
  "level":[
    {
      "id":1,
      "server":[
        {"score":33,"name":"Car"},
        {"score":72,"name":"Bus"},
      ]
    }   
  ]
}
1
  • Did you try searching Google? Something like, although it may sound weird: "android parse json from url into list"? Commented Jun 11, 2017 at 8:33

2 Answers 2

1

Do you know how to retrieve the data? After you retrieve the data, parsing it is very simple. To get each individual item with its attributes I would use the following code:

String responseFromUrl;
JSONObject JSONResponse = new JSONObject(responseFromURL);
JSONArray level = JSONResponse.getJSONArray("level");

//The following loop goes through each object in "level". This is nessecary if there are multiple objects in "level".
for(int i=0; i<level.length(); i++){
    JSONObject object = level.get(i);
    int id = object.getInteger("id");
    JSONArray server = object.getJSONArray("server");

    //This second loop gets the score and name for each object in "server"
    for(int j=0; j<server.length(); j++){
        JSONObject serverObject = server.get(i);
        int score = serverObject.getInteger("score");
        String name = serverObject.getString("name");
    }
}

Obviously replace "responseFromUrl" with the JSON response from the url in string format. If you don't know why I used JSONObject, JSONArray, String, Integer, etc., or are just confused about this, Udacity has a good course for making http connections and parsing JSON responses from APIs. Link to Udacity Course

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much Matt32.
0

You can use the gson library to convert json to an java object

Download the latest jar and import into your project, currently you can download the latest at this link: https://repo1.maven.org/maven2/com/google/code/gson/gson/2.8.1/gson-2.8.1.jar

After, this will help you: https://stackoverflow.com/a/23071080/4508758

Hugs!

1 Comment

Thank you DigaoParceiro.

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.