Retrieving nested arrays values with JSON Java

前端 未结 1 702
执笔经年
执笔经年 2020-12-21 17:50

I\'m struggling to retrieve some values from a JSON file formatted like this one:

{
  \"search\": {
    \"entry\": [
      {
        \"found\": \"identity=94         


        
相关标签:
1条回答
  • 2020-12-21 18:24

    Libraries used:

    import org.json.simple.JSONArray;
    import org.json.simple.JSONObject;
    

    Check the below code and step wise parsing

        JSONObject search = (JSONObject) jsonObject.get("search");//1
        JSONArray entry = (JSONArray) search.get("entry");//2
        for (int i = 0; i < entry.size(); i++) {
            JSONObject jsonObject1 = (JSONObject) entry.get(i);//3
            JSONArray jsonarray1 = (JSONArray) jsonObject1.get("attribute");//4
            for (int j = 0; j < jsonarray1.size(); j++) {
                System.out.println(((JSONObject) jsonarray1.get(j)).get(
                        "value").toString());//5
    
            }
    
        }
    

    It will give the values mentioned step wise:

    1) {"entry":[{"found":"identity=9454532,l=big,ton=grand,k=molvi","attribute":[{"name":"firstname","value":["Lucas"]},{"name":"lastname","value":["Brandon"]}]}],"return":{"code":0,"count":1,"message":"Success"}}

    2) [{"found":"identity=9454532,l=big,ton=grand,k=molvi","attribute":[{"name":"firstname","value":["Lucas"]},{"name":"lastname","value":["Brandon"]}]}]

    3) {"found":"identity=9454532,l=big,ton=grand,k=molvi","attribute":[{"name":"firstname","value":["Lucas"]},{"name":"lastname","value":["Brandon"]}]}

    4) [{"name":"firstname","value":["Lucas"]},{"name":"lastname","value":["Brandon"]}]

    5) ["Lucas"] and ["Brandon"]

    So basically you have to take care of JSONObject and JSONArray respectively and do the parsing accordingly.

    0 讨论(0)
提交回复
热议问题