[英]How do I pull the string name array from this json object?
{ “类别”:[{ “ID”: “1”, “名称”: “ASDF”}]}
它是我的JSON字符串。 我想获取名称键的值..如何在android中做到这一点? 求助
大段引用
这是您的带有异常处理和null检查的json解析:
//get json string first from the response and convert it into json object
JSONObject object;
try {
object = new JSONObject("yourjsonstring");
} catch (JSONException e) {
e.printStackTrace();
object = null;
}
JSONArray jsonArray;
if (object != null) {
Object categoryObject = null;
try {
categoryObject = object.get("categories");
} catch (JSONException e) {
e.printStackTrace();
categoryObject = null;
}
if (categoryObject != null) {
if (categoryObject instanceof JSONArray) {
//if categoriew array having more than 1 items
jsonArray = (JSONArray) categoryObject;
} else {
//if categories array having single item
jsonArray = new JSONArray();
jsonArray.put((JSONObject) categoryObject);
}
JSONObject categoryItemObj = null;
for (int i = 0; i < jsonArray.length(); i++) {
try {
categoryObject = jsonArray.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
categoryItemObj = null;
}
if (categoryItemObj != null) {
String id = "";
try {
id = categoryItemObj.getString("id");
} catch (JSONException e) {
e.printStackTrace();
id = "";
}
String name;
try {
name = categoryItemObj.getString("name");
} catch (JSONException e) {
e.printStackTrace();
name = "";
}
}
}
}
}
您可以使用Gson的fromJson()方法将其映射到POJO,然后从中提取名称。
类型listType = new TypeToken>(){}。getType(); new Gson()。fromJson(“ [{{id”:“ 1”,“ name”:“ asdf”}]“”,listType);
您将获得List<Category>
,然后从列表中提取名称。
之后,您必须从JSONObject获取数组。 在这里,您将从上述数组中获取所有值。
JSONObject object = new JSONObject(yourjsonstring);
JSONArray id = object.getJSONArray("id");
JSONArray name = object.getJSONArray("name");
for(int i=0;i<id.length; i++){
String strid=id.getString(i);
String strname=name.getString(i);
}
解析此json字符串。
使用Gson解析器,例如: https : //code.google.com/p/google-gson/
或者,您可以使用Android的JSONObject。 这是一个教程-http: //www.javacodegeeks.com/2013/10/android-json-tutorial-create-and-parse-json-data.html
public class HttpAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
return GET(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();
try {
JSONObject json = new JSONObject(result);
JSONArray articles = json.getJSONArray("categories");
String name=new String[json.getJSONArray("images").length()]; //initializtion
for(int i=0;i<json.getJSONArray("categories").length();i++){
name[i] = (articles.getJSONObject(i).optString("name"));//here u got your value all name
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
使用execute调用asynctask并将URL传递给它
new HttpAsyncTask().execute(url);
从UI线程
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.