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 :)

3
  • 1
    Consider using something like Jackson to unmarshal JSON to Java object structures. Commented Dec 14, 2016 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 Commented Dec 14, 2016 at 13:44
  • Possible duplicate of Reading a Json Array in android Commented Dec 14, 2016 at 13:49

2 Answers 2

0
JSONArray circuitList = (JSONArray) jsonObject.get("CircuitList");
JsonArray parts = circuitList.getJsonObject(0).getJsonArray("parts");

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

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

Comments

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.

Comments

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.