简体   繁体   中英

how to parse this in android with json

I want to parse this json in android. Can you help me how to parse, if i need to start from head to parse or from results for this I don't know. Can you help me

{ 
"head": 
   { 
    "link": [], 
    "vars": ["city", "country"] 
    }, 
"results": 
    { 
        "distinct": false, 
        "ordered": true, 
        "bindings": 
            [ 
                { 
                    "city": 
                        { 
                            "type": "uri",
                             "value": "http://dbpedia.org/resource/Ferizaj"
                        } ,
                    "country": 
                        { 
                        "type": "uri", 
                        "value": "http://dbpedia.org/resource/Kosovo" 
                        }
                 } 
            ] 
    } 
 }

Okay, first of all the JSON string you've given is invalid. I've written my answer based on the correct version of the JSON string that you have provided

 { 
"head": 
   { 
    "link": [], 
    "vars": ["city", "country"] 
    }, 
"results": 
    { 
        "distinct": false, 
        "ordered": true, 
        "bindings": 
            [ 
                { 
                    "city": 
                        { 
                            "type": "uri",
                             "value": "http://dbpedia.org/resource/Ferizaj"
                        } ,
                    "country": 
                        { 
                        "type": "uri", 
                        "value": "http://dbpedia.org/resource/Kosovo" 
                        }
                 } 
            ] 
    } 
 }

Now, to get the "values", you'll need to do this.

JSONObject jsonObject = new JSONObject(response);
JSONObject results = jsonObject.getJSONObject("results");
JSONArray bindings = results.getJSONArray("bindings");
for (int i = 0; i < bindings.length(); i++) {
    JSONObject binding = bindings.getJSONObject(i);
    JSONObject city = binding.getJSONObject("city");
    // Get value in city
    String cityValue = city.getString("value");
    Log.d("CITY", cityValue);
    JSONObject country = binding.getJSONObject("country");
    // Get value in country
    String countryValue = country.getString("value");
    Log.d("COUNTRY", countryValue);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM