How to get json array values in android?

前端 未结 3 704
-上瘾入骨i
-上瘾入骨i 2021-01-01 01:05

JSON response value looks like this \"types\" : [ \"sublocality\", \"political\" ]. How to get the first value of the types or how to get the word sublocality?<

相关标签:
3条回答
  • 2021-01-01 01:21

    I would insist you to use GSON. I had created a demo for parsing the same map response. You can find the complete demo here. Also I had created a global GSON parser class that can be used to parse any response that is in JSON with ease.

    0 讨论(0)
  • 2021-01-01 01:29

    You should parse that JSON to get those values. You can either use JSONObject and JSONArray classes in Android or use a library like Google GSON to get the POJOs from JSON.

    0 讨论(0)
  • 2021-01-01 01:36
    String string = yourjson;
    
    JSONObject o = new JSONObject(yourjson);
    JSONArray a = o.getJSONArray("types");
    for (int i = 0; i < a.length(); i++) {
        Log.d("Type", a.getString(i));
    }
    

    This would be correct if you were parsing only the line you provided above. Note that to access types from GoogleMaps geocode you should get an array of results, than address_components, then you can access object components.getJSONObject(index).

    This is a simple implementation that parses only formatted_address - what I needed in my project.

    private void parseJson(List<Address> address, int maxResults, byte[] data)
    {
        try {
            String json = new String(data, "UTF-8");
            JSONObject o = new JSONObject(json);
            String status = o.getString("status");
            if (status.equals(STATUS_OK)) {
    
                JSONArray a = o.getJSONArray("results");
    
                for (int i = 0; i < maxResults && i < a.length(); i++) {
                    Address current = new Address(Locale.getDefault());
                    JSONObject item = a.getJSONObject(i);
    
                    current.setFeatureName(item.getString("formatted_address"));
                    JSONObject location = item.getJSONObject("geometry")
                            .getJSONObject("location");
                    current.setLatitude(location.getDouble("lat"));
                    current.setLongitude(location.getDouble("lng"));
    
                    address.add(current);
                }
    
            }
        catch (Throwable e) {
            e.printStackTrace();
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题