在尝试了几个星期后,在这里找到了无数的例子,似乎遍及整个网络,我被难住了。我可以从Google Shopping检索到所需的搜索结果:
{ "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(结果)的输出:
[{"product":{"brand":"The Doctor's, "title":"The Doctor's..."}}]发布于 2011-09-03 12:34:57
一个适用于所有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很不错,但只在API10和更高版本中可用。所以它可能对你有用,也可能对你没用。
发布于 2011-09-03 12:23:10
您应该使用JsonReader来读取json字符串。它非常简单,并且有很好的文档和非常好的示例..here
https://stackoverflow.com/questions/7291047
复制相似问题