【问题标题】:Retrieving string from nested objects in JSON file || Android从 JSON 文件中的嵌套对象中检索字符串 ||安卓
【发布时间】:2015-03-16 14:27:17
【问题描述】:

我在尝试访问 JSON 文件中的某些值时遇到问题。 该文件有多个对象存储在一个数组中。

我需要返回的值是“maxspeed”字符串中的“60”。 当当前代码在调试中执行时,它只是保持在一个循环中。*不知道为什么)

“结果”字符串的值是整个json文件。

谁能解释如何访问这个值?

谢谢。

JSON:

{
  "version": 0.6,
  "generator": "Overpass API",
  "osm3s": {
    "timestamp_osm_base": "2015-03-16T00:27:03Z",
    "copyright": "The data included in this document is from www.openstreetmap.org. The data is made available under ODbL."
  },
  "elements": [

{
  "type": "node",
  "id": 768053039,
  "lat": 54.9526671,
  "lon": -7.7273348
},
{
  "type": "node",
  "id": 768053040,
  "lat": 54.9498094,
  "lon": -7.7176056
},
{
  "type": "node",
  "id": 768053041,
  "lat": 54.9497066,
  "lon": -7.7173174
},
{
  "type": "node",
  "id": 768053043,
  "lat": 54.9495658,
  "lon": -7.7170937
},
{
  "type": "node",
  "id": 768053044,
  "lat": 54.9495035,
  "lon": -7.7169816
},
{
  "type": "node",
  "id": 791492493,
  "lat": 54.9494183,
  "lon": -7.7168205
},
{
  "type": "node",
  "id": 795319854,
  "lat": 54.9510427,
  "lon": -7.7218262
},
{
  "type": "node",
  "id": 795320324,
  "lat": 54.9509153,
  "lon": -7.7213706
},
{
  "type": "node",
  "id": 1922546572,
  "lat": 54.9502165,
  "lon": -7.7190169
},
{
  "type": "node",
  "id": 1922546679,
  "lat": 54.9504739,
  "lon": -7.7199078
},
{
  "type": "node",
  "id": 1922546692,
  "lat": 54.9500860,
  "lon": -7.7185174
},
{
  "type": "node",
  "id": 1922602861,
  "lat": 54.9517250,
  "lon": -7.7241644
},
{
  "type": "node",
  "id": 1922622063,
  "lat": 54.9514357,
  "lon": -7.7231690
},
{
  "type": "node",
  "id": 2673934802,
  "lat": 54.9498543,
  "lon": -7.7177617
},
{
  "type": "way",
  "id": 64273241,
  "nodes": [
    768053039,
    1922602861,
    1922622063,
    795319854,
    795320324
  ],
  "tags": {
    "highway": "secondary",
    "maxspeed": "60",
    "name": "Port Road",
    "oneway": "no",
    "ref": "R229"
  }
},
{
  "type": "way",
  "id": 64887990,
  "nodes": [
    795320324,
    1922546679,
    1922546572,
    1922546692,
    2673934802,
    768053040,
    768053041,
    768053043,
    768053044,
    791492493
  ],
  "tags": {
    "highway": "secondary",
    "maxspeed": "60",
    "name": "Port Road",
    "oneway": "no",
    "ref": "R229"
  }
}

  ]
}

代码:

protected Void doInBackground(String... params) {
            android.os.Debug.waitForDebugger();
            //String url_select = "http://yoururlhere.com";

            StringBuilder builder = new StringBuilder(); 
            HttpClient client = new DefaultHttpClient(); 
            HttpGet httpGet = new HttpGet(encode2); 

            try { 
                HttpResponse response = client.execute(httpGet); 
                StatusLine statusLine = response.getStatusLine(); 
                int statusCode = statusLine.getStatusCode(); 

                if (statusCode == 200) { 
                    HttpEntity entity = response.getEntity(); 
                    InputStream content = entity.getContent(); 
                    BufferedReader reader = new BufferedReader(new InputStreamReader(content)); 
                    String line; 

                    while ((line = reader.readLine()) != null) { 

                        builder.append(line); } } 
                else { 
                    Log.e("==>", "Failed to download file"); } 
                } catch (ClientProtocolException e) { 
                    e.printStackTrace(); 
                } catch (IOException e) { 
                    e.printStackTrace(); } 
                result = builder.toString();
            return null;
        } // protected Void doInBackground(String... params)

        protected void onPostExecute(Void v) {
            //parse JSON data
            try {
                JSONObject parentObject = new JSONObject(result);

                JSONArray speedJSON = parentObject.getJSONArray("elements"); 

                JSONObject maxspeed = parentObject.getJSONObject("maxspeed");
                System.out.print(""+maxspeed.toString()+"\n");
                //String[] elementNames = JSONObject.(speedJSON);
                System.out.printf("%d ELEMENTS IN CURRENT OBJECT:\n", speedJSON.length());
                for (int i = 0; i< speedJSON.length(); i++)
                {
                    String value = speedJSON.getString(i);
                    System.out.printf("name=%s, value=%s\n", speedJSON.get(i), value);
                }
                //And then read attributes like      
               /* for(int i = 0; i<speedJSON.length(); i++){
                    JSONObject child = speedJSON.getJSONObject(i);
                    if(child.getString("type").equals("way")){
                        JSONObject tag = speedJSON.getJSONObject(i);
                        JSONObject maxspeed = tag.getJSONObject("tags");
                        String speed = maxspeed.getString("maxspeed"); 
                        txtSpeed.setText(speed);
                    }
                }*/

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 
           /* try {
                JSONArray jArray = new JSONArray(result);    
                for(int i=0; i < jArray.length(); i++) {

                    JSONObject jObject = jArray.getJSONObject(i);

                    String speedLimit = jObject.getString("maxspeed");
                    txtSpeed.setText(speedLimit);
                } // End Loop

                this.progressDialog.dismiss();

            } catch (JSONException e) {
                Log.e("JSONException", "Error: " + e.toString());
            } // catch (JSONException e)
*/      } // protected void onPostExecute(Void v)

    }

【问题讨论】:

    标签: java android json parsing openstreetmap


    【解决方案1】:

    好的,您的第一个问题是,并非“元素”数组中的所有 JSONObject 都具有最大速度属性。第二个问题是您没有正确地迭代 JSONArray。

    让我们从第二个问题开始:

    for (int i = 0; i < speedJSON.length(); i++) {
        JSONObject element = (JSONObject) speedJSON.get(i);
    }
    

    现在您的元素是 JSONObject,其中包含您的不同属性(类型、id、lon、...) 要解决您的第一个问题,您可以检查 JSONObject 是否包含您要查找的密钥 (maxspeed)

    if (!element.isNull("tags") {
        JSONObject tags = (JSONObject)element.get("tags");
        if (!tags.isNull("maxspeed") {
            String maxspeed = tags.getString("maxspeed");
        }
    } else {
        //Your error handling here...
    }
    

    希望这会有所帮助!

    【讨论】:

    • 感谢您的回复!当我测试代码时,它围绕每个数组元素循环,但从未找到“maxspeed”。我必须先获取“标签:方式”对象吗?
    • 哦,是的,对不起,我忘了添加这个。检查标签对象是否存在并从中获取最大值。
    • 类似:" for (int i = 0; i
    • 为混乱的评论道歉:/
    猜你喜欢
    • 1970-01-01
    • 2017-08-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-19
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    相关资源
    最近更新 更多