2013-06-04 167 views
0

我试图解析JSON使用jsontokener 这是我的jsontokener代码:的Android解析JSON对象使用jsontokener

try { 
     JSONObject jObj = (JSONObject) new JSONTokener(strJson).nextValue(); 
     String query = jObj.getString("query"); 
     JSONArray location = jObj.getJSONArray("locations"); 
     TextView tv = (TextView) findViewById(R.id.dummy_text); 
     tv.setText(query); 
    } catch (JSONException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
     TextView tv = (TextView) findViewById(R.id.dummy_text); 
     tv.setText("Wrong"); 
    } 

这是我第一次strJson:

 String strJson = "{" 
      + " \"query\": \"Pizza\", " 
      + " \"locations\": [ 94043, 90210 ] " 
      + "}"; 

,它会显示

比萨

,我试图改变strJson是这样的:

 String strJson = "{" 
      + " \"component\": " 
       + "{" 
        + " \"query\": \"Pizza\", " 
        + " \"locations\": [ 94043, 90210 ] " 
       + "}" 
      + "}"; 

,它会显示

错误

意味着代码输入捕捉。 请帮助我如何提高我的代码,以便它可以在组件中查询。

回答

1

finnaly我找到了答案,我只是提高代码是这样的:

try { 
     JSONObject jObj = (JSONObject) new JSONTokener(strJson).nextValue(); 
     JSONObject obj = jObj.getJSONObject("component"); 
     String query = obj.getString("query"); 
     //JSONArray location = jObj.getJSONArray("locations"); 
     TextView tv = (TextView) findViewById(R.id.dummy_text); 
     tv.setText(query); 
    } catch (JSONException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
     TextView tv = (TextView) findViewById(R.id.dummy_text); 
     tv.setText("Wrong"); 
    } 
1

正常情况下没有必要直接使用JSONTokener类。这实际上只是JSONObject的一个Helper类。只需直接从字符串创建一个新的JSON对象

try {  
    JSONObject component = new JSONObject(strJson).getJSONObject("component"); 
    String query = component.getString("query"); 
    JSONArray locations = component.getJSONArray("locations"); 
    // Do something ... 

} catch(JSONException e) { 
    // Do something ... 
}