您好我正在尝试获取具有jsonarray属性的json响应
喜欢(例如:{A:一,B:[{a:one,b:two},{a:two,b:one}]})我试图获得
a:一个和b:仅两个值。但我的logcat说错误:
我希望在textview中为我的产品详细信息视图获取此值...
我的编码是:
private class GetProductDetails extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
dialog_pro = new ProgressDialog(Product_Detail_Activity.this);
dialog_pro.setMessage("Please wait...");
dialog_pro.setCancelable(false);
dialog_pro.show();
}
@Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(BaseURL);
//Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
name = jsonObj.getString("name");
JSONArray items = new JSONArray("custom_attributes");
for (int i = 0; i < items.length(); i++) {
JSONObject c = items.getJSONObject(i);
String atrr = c.getString("attribute_code");
if(atrr.equalsIgnoreCase("short_description")) {
des = c.getString("value");
}
}
}catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
// pro_name.setText("Json error:" + e.getMessage());
}
});
}
} else {
//Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
// AppController.getPermission().addToRequestQueue(jsonObj);
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
/**
* Updating parsed JSON data into ListView
* */
if (dialog_pro.isShowing())
dialog_pro.dismiss();
pro_name.setText(name);
short_desc.setText(des);
}
}
答案 0 :(得分:1)
基于你的JSON
try {
JSONObject responseObject = new JSONObject(response);
String A= responseObject.getString("A");
JSONArray bArray= responseObject.getJSONArray("B");
for(int i=0;i<bArray.length();i++){
JSONObject innerObject=bArray.getJSONObject(i);
String a= innerObject.getString("a");
String b= innerObject.getString("b");
}
} catch (Exception e) {
e.printStackTrace();
}
在您的代码中,您应该更改 JSONArray items = new JSONArray(“custom_attributes”); 。您应该使用object.getJSONArray()从 jsonObj 对象获取 custom_attributes数组。
答案 1 :(得分:0)
第一个问题 - RecyclerView:没有连接适配器;跳过布局 - &gt; 只需先设置一个空的适配器,一旦有了数据就立即更新(这对我有用) 对于您的第二个问题-Json解析错误:类型java.lang.String的值custom_attributes无法转换为JSONArray-&gt;
您发布的例如{A:一,B:[{a:one,b:two},{a:two,b:one}]}“ 它不是有效的json格式