解析谷歌购物Json搜索结果

时间:2011-09-03 03:48:39

标签: android json parsing

经过几周的尝试,在这里找到了很多例子,似乎在整个网络上,我很难过。我可以从Google购物中检索所需的搜索结果:

{ "items": [  {   "product": {
"title": "The Doctor's BrushPicks Toothpicks 250 Pack",
"brand": "The Doctor's"  } } ] }

我的问题是我将数据放在一个字符串中,如何提取这两个值(标题,品牌)以便在程序的其他地方使用它们?

以下是有问题的课程:     公共类HttpExample扩展了Activity {

TextView httpStuff;
DefaultHttpClient client;
JSONObject json;


final static String URL = "https://www.googleapis.com/shopping/search..."; 

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
    setContentView(R.layout.httpex);
    httpStuff = (TextView) findViewById(R.id.tvHttp);
    client = new DefaultHttpClient();
    new Read().execute("items");

}

public JSONObject products(String upc)  throws ClientProtocolException, IOException, JSONException {
    StringBuilder url = new StringBuilder(URL);
    url.append(upc);

    HttpGet get = new HttpGet(url.toString());
    HttpResponse r = client.execute(get);
    int status = r.getStatusLine().getStatusCode();
    if (status == 200) {
        HttpEntity e = r.getEntity();
        String data = EntityUtils.toString(e);
        JSONObject timeline = new JSONObject(data);
        return timeline;
    } else {
        Toast.makeText(HttpExample.this, "error", Toast.LENGTH_SHORT);
        return null;
    }
}

public class Read extends AsyncTask<String, Integer, String> {

    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub
        try {
            String upc = ExportMenuActivity.upc;
            json = products(upc);
            return json.getString(params[0]);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

@Override
protected void onPostExecute(String result){
    httpStuff.setText(result);
}
}

}

httpStuff.setText(result)的输出:

[{"product":{"brand":"The Doctor's, "title":"The Doctor's..."}}]

2 个答案:

答案 0 :(得分:0)

您应该使用JsonReader来读取json字符串。它非常简单,并且有很好的样本。here

答案 1 :(得分:0)

适用于所有Android版本的解决方案如下所示:

JSONObject products = products(jsonStr);
JSONArray itemArray = products.getJSONArray("items");
for(int i=0; i<itemArray.length(); i++) {
  if(itemArray.isNull(i) == false) {
    JSONObject item = itemArray.getJSONObject(i);
    String title = item.getString("title");
    String brand = item.getString("brand");
  }
}

JsonReader很不错,但仅适用于API 10及更高版本。所以它可能会或可能不适合你。

相关问题