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"},
      ]
    }   
  ]
}
Johny
  • 45
  • 10
  • Did you try searching Google? Something like, although it may sound weird: "android parse json from url into list"? – yakobom Jun 11 '17 at 08:33

2 Answers2

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

Matt32
  • 26
  • 4
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!

Rodrigo João Bertotti
  • 5,179
  • 2
  • 23
  • 34