我想用json
显示我的RecyclerView
回复,但它没有显示任何内容!
这是我的json
:
[
{
"key": "test",
"vals": [
{
"Id": 0,
"Group": "test",
"Type": 0,
"Name": "ram",
"Value": "8",
"Sort": 2
},
{
"Id": 0,
"Group": "test",
"Type": 0,
"Name": "cpu",
"Value": "2.4",
"Sort": 1
}
]
},
{
"key": "mobile",
"vals": [
{
"Id": 0,
"Group": "mob",
"Type": 0,
"Name": "camera",
"Value": "8",
"Sort": 5
},
{
"Id": 0,
"Group": "mob",
"Type": 0,
"Name": "cpu",
"Value": "4",
"Sort": 0
},
{
"Id": 0,
"Group": "mob",
"Type": 0,
"Name": "Ram",
"Value": "4",
"Sort": 0
}
]
这是我的Java
代码:
JSONObject jsonObject = new JSONObject(s);
JSONArray array = jsonObject.getJSONArray("key");
for(int i=0;i<array.length();i++) {
JSONObject o = array.getJSONObject(i);
ListItem_spec item = new ListItem_spec(o.getString("id"),o.getString("group"),o.getString("type"),o.getString("name"),o.getString("value"),o.getString("sort"),o.getString("key"));
listItems.add(item);
}
adapter = new MyAdapter_spec(listItems,getContext());
recyclerView.setAdapter(adapter);
我该如何解决这个问题?
答案 0 :(得分:3)
您正在尝试解析此类结构:
{
"key": [
{
"id": 0,
"group": "test",
"type": 0,
"name": "ram",
"value": "8",
"sort": 2,
"key": "someKey"
},
...
]
}
但你有一个json
结构。试试这段代码:
JSONArray array = new JSONArray(s);
for(int i=0; i < array.length(); i++) {
JSONObject valsObj = array.getJSONObject(i);
JSONArray valsArray = valsObj.getJSONArray("vals");
String key = valsObj.getString("Key");
for(int j=0; j < valsArray.length; j++) {
JSONObject o = valsArray.getJSONObject(j);
ListItem_spec item = new ListItem_spec(o.getString("Id"), o.getString("Group"), o.getString("Type"), o.getString("Name"), o.getString("Value"), o.getString("Sort"), key);
listItems.add(item);
}
}
adapter = new MyAdapter_spec(listItems, getContext());
recyclerView.setAdapter(adapter);
答案 1 :(得分:0)
您是否已将布局管理器附加到回收站视图?
答案 2 :(得分:0)
如果你想使用Gson ..你可以像这样实现
创建模型
public class ListItem_spec{
private List<Vals> vals;
private String key;
public List<Vals> getVals (){
return vals;
}
public String getKey (){
return key;
}
}
public class Vals
{
private String Name;
private String Sort;
private String Value;
private String Type;
private String Id;
private String Group;
public String getName (){
return Name;
}
public String getSort (){
return Sort;
}
public String getValue (){
return Value;
}
public String getType (){
return Type;
}
public String getId (){
return Id;
}
public String getGroup (){
return Group;
}
}
然后使用Gson()
List< ListItem_spec > listItems = new Gson().fromJson(YOUR_JSON,new TypeToken<List<ListItem_spec>>(){}.getType());
adapter = new MyAdapter_spec(listItems, getContext());
recyclerView.setAdapter(adapter);
//dont forget to add notifyDataSetChanged();
adapter.notifyDataSetChanged();