0

So I'm currently building a game, and I'm trying to parse this in the game. Now this is how a part of it looks like:

{
    "CircuitList": [    
        {    
            "name": "GP SILVERSTONE",
            "location": "ENGLAND",
            "laps": 57,
            "Parts": 
                [
                    {   
                        "1":{
                        "type": "straight",
                        "length": 800
                    },
                        "2": {
                        "type": "sharpturn",
                        "length": 200
                    },  

Now this is followed by more parts. Right now, I've parsed the json file, and used

JSONArray Silverstoneparts = (JSONArray) jsonObject.get("Parts");

to create a array with all the parts. But I don't know how to read out the types and lengths, so if there is anyone willing to help, like push me gently into the right direction, it would be highly appreciated :)

Pavneet_Singh
  • 36,884
  • 5
  • 53
  • 68
  • 1
    Consider using something like Jackson to unmarshal JSON to Java object structures. – lexicore Dec 14 '16 at 13:36
  • create an object `obj` for the required structure, in your case, the object will have type and length. Now, parts is an array of objects, each of which contains a map from "id" to `obj`. You can then use Jackson or gson or some library to serialize and deserialize – gaganbm Dec 14 '16 at 13:44
  • Possible duplicate of [Reading a Json Array in android](http://stackoverflow.com/questions/4244879/reading-a-json-array-in-android) – Bryan Dec 14 '16 at 13:49

2 Answers2

0

You can try parsing the JSON using gson library. You should define a data struct with nested arrays/properties as per your JSON data and serialise the JSON data to native object.

Native java object will help you read the parsed arrays and other properties in your code rather being relying on keys and running loops within loops to extract the values.

Gurdev Singh
  • 1,996
  • 13
  • 11
0
JSONArray circuitList = (JSONArray) jsonObject.get("CircuitList");
JsonArray parts = circuitList.getJsonObject(0).getJsonArray("parts");

It's recommend to use JsonObject to build json string.

thepaulo
  • 370
  • 4
  • 10