1

This is my JSON output. I am trying to return the "id": "9040" from instructions but am having trouble

{
  "packages": [
    {
      "instructions": [
        {
      "id": "9040",
      "fn": "test.xml",
      "@type": "down",
      "fp": ""
    }
  ],
  "id": "47968",
  "time": 1396036698630,
  "priority": 0
}

] }

Here is my code that returns the "Package" -> "Id"

         JSONObject jObject = new JSONObject(json);
         JSONArray jsonMainNode = jObject.optJSONArray("packages");
         int lengthJsonArr = jsonMainNode.length();  
         for(int i=0; i < lengthJsonArr; i++) 
         {
             /****** Get Object for each JSON node.***********/
             JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
             fileid  = Integer.parseInt(jsonChildNode.optString("id").toString());
             if (fileid > 0 )

             Log.i("JSON parse", "id = "+ fileid);
        }

Any help would be much appreciated.

Thank you

1 Answer 1

1

You forget about JSONArray instructions

    {
    "packages": [
        {
            "instructions": [
                {
                    "id": "9040",
                    "fn": "test.xml",
                    "@type": "down",
                    "fp": ""
                }
            ],
            "id": "47968",
            "time": 1396036698630,
            "priority": 0
        }
    ]
}

To parse

JSONObject jObject = new JSONObject(json);
JSONArray jsonMainNode = jObject.optJSONArray("packages");
JSONObject jb = (JSONObject) jsonMainNode.get(0);
JSONArray instructions = jb.getJSONArray("instructions");
JSONObject jb1 =  (JSONObject) instructions.get(0);
String id = jb1.getString("id");
Sign up to request clarification or add additional context in comments.

1 Comment

@motti10 you are welcome. You could also use String id = jb1.optString("id");

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.