这是我从服务器收到的JSON。您会注意到下面代码中的数组'rows'数组有一个名称值对,偶尔也有一个没有名称的布尔值。我没有问题使用永远不包含偶然boolean
的JSON解析它。
[{
"label": "Overview",
"rows": [[{
"name": "name"
},
false],
[{
"name": "emailAddress"
},
{
"name": "phoneNumber"
}],
[{
"name": "website"
},
false],
[{
"name": "billingAddress"
},
{
"name": "shippingAddress"
}]]
},
{
"label": "Details",
"rows": [[{
"name": "type"
},
{
"name": "sicCode"
}],
[{
"name": "industry"
},
false],
[{
"name": "description",
"fullWidth": true
}]]
}]
这是我的Java代码。我用Volley。
public void displayFields(){
RequestQueue queue = Volley.newRequestQueue(this.getApplicationContext());
String url = "some-url-goes-here";
CustomJsonArrayRequest request = new CustomJsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Log.d("LoginActivity", "Recieved Success Response: " + response.toString());
DisplayPanel[] displayPanels = new GSONBuilder().getDisplayPanelsFromJSON(response.toString());
for(int i=0;i<displayPanels.length;i++){
DisplayPanel panel = displayPanels[i];
DisplayField[][] rows = panel.getRows();
for(int j=0;j<rows.length;j++){
DisplayField[] fieldsinRow = rows[j];
for(int k=0;k<fieldsinRow.length;k++){
DisplayField field = fieldsinRow[k];
Log.d("LoginActivity", "Field has value: " + field.getName());
}
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("LoginActivity", "ERROR getting jsonarray" + error.getMessage());
}
});
request.setCustomHeader("custom-header-name", "custom-header-value");
queue.add(request);
}
在上面的代码中CustomJsonArrayRequest
只是从Volley库扩展JsonArrayRequest
,只添加一个允许设置自定义标头的方法。 DisplayField
只是一个对象,表示json中的名称 - 值对(就在布尔值之前)
public class DisplayField {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
DisplayPanel是顶级数组项(包含标签和行)。这是代码。
public class DisplayPanel{
private String label;
private DisplayField[][] rows;
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public void setRows(DisplayField[][] displayFields){
this.rows = displayFields;
}
public DisplayField[][] getRows(){
return rows;
}
}
我做错了什么?当我运行这个时,我得到了一个
java.lang.NullPointerException:尝试获取null数组的长度