我正在尝试在安卓应用程序中显示json数据,但我遇到了困难,我认为这可能与json文件的格式有关,因为我想要在headers数组中获取名称和代码的值。而且它不起作用
这是json文件
{
"status": "SUCCESS",
"headers":
{
"id": "4",
"name": "GLO",
"code": "GLO",
"background_color_code": "15B709",
"text_color_code": "ffffff",
"statusMessage": "Hi +234805, an ACCESS FEE of N20.00 will be charged in order to access this Platform"
},
"statusMessage": "Movies Loaded successfully",
"caption": "Discover"
}这是java代码。
protected ArrayList<HashMap<String, String>> doInBackground(Void... arg0) {
ArrayList<HashMap<String, String>> categoryList = new ArrayList<HashMap<String, String>>();
jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(URL_CATEGORY);
try {
JSONObject categories =json.getJSONObject("headers");
String state = categories.getString("name");
String status = categories.getString("code");
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_PIC, state);
map.put(TAG_NOTE, status);
categoryList.add(map);
}catch (Throwable e){
e.printStackTrace();
}
return categoryList;
}这就是错误
07-25 11:05:50.766 15683-15697/com.example.cann I/System.out﹕ close [socket][/10.187.206.124:36118]
07-25 11:05:50.781 15683-15702/com.example.cann W/System.err﹕ org.json.JSONException: Value at headers of type java.lang.String cannot be converted to JSONObject
07-25 11:05:50.782 15683-15702/com.example.cann W/System.err﹕ at org.json.JSON.typeMismatch(JSON.java:100)
07-25 11:05:50.782 15683-15702/com.example.cann W/System.err﹕ at org.json.JSONObject.getJSONObject(JSONObject.java:613)
07-25 11:05:50.782 15683-15702/com.example.cann W/System.err﹕ at com.example.cann.CategoryActivity$LoadComments.doInBackground(CategoryActivity.java:81)
07-25 11:05:50.782 15683-15702/com.example.cann W/System.err﹕ at com.example.cann.CategoryActivity$LoadComments.doInBackground(CategoryActivity.java:60)发布于 2016-07-25 19:04:55
您可以尝试使用
try {
JSONObject reader = new JSONObject(Your_URL);
JSONArray jsonArray = reader.getJSONArray("headers");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject e = jsonArray.getJSONObject(i);
String name= e.getString("name");
}
} catch (JSONException e) {
e.printStackTrace();
}发布于 2016-07-25 18:53:35
尝尝这个
try {
JSONObject rootJsonObject = new JSONObject(response);
if (rootJsonObject.getString("status").equalsIgnoreCase("SUCCESS")) {
JSONObject headerJsonObject = new JSONObject(rootJsonObject.getString("headers"));
String name = headerJsonObject.getString("name");
String code = headerJsonObject.getString("code");
}
} catch (JSONException e) {
e.printStackTrace();
}发布于 2016-07-25 18:56:58
您可以使用Gson (Complete Tutorial)或Jackson (Complete Tutorial)
https://stackoverflow.com/questions/38565619
复制相似问题