我有 JSON ,我希望将第一个对象的数据合并到第二个对象
{
"ViewId": {
"56": {
"ViewId": "56",
"Name": "hi",
"param": "value"
},
"88": {
"ViewId": "88",
"Name": "hi2",
"param": "value2"
}
},
"que": [
{
"RId": "123",
"ViewId": "88",
"Count": 0
},
{
"RId": "456",
"ViewId": "56",
"Count": 0
}
]
}
基本上,我正在制作ArrayList,如何将ViewId数据添加到que中。 我想以下列方式合并JSON:
{
"que": [
{
"RId": "123",
"ViewId": "88",
"Name": "hi2",
"param": "value2",
"Count": 0
},
{
"RId": "456",
"ViewId": "56",
"Name": "hi",
"param": "value",
"Count": 0
}
]
}
答案 0 :(得分:1)
JSONObject ViewIdJsnObject = new JSONObject(); //replace new JSONObject() with ViewId Json Object here
JSONArray queArray = new JSONArray();//replace new JSONArray() with actual json array;
//Traverse through all que objects in array
if(queArray != null && queArray.length() > 0){
for(int i=0; i<queArray.length(); i++){
try {
JSONObject queObj = queArray.getJSONObject(i);
String queViewId = queObj.getString("ViewId"); //ViewId of que object at position i
JSONObject viewIdObj = ViewIdJsnObject.getJSONObject(queViewId); //get json object against ViewId
if(viewIdObj != null) {
//Now add these value to que object at position i
String name = viewIdObj.getString("Name");
String param = viewIdObj.getString("param");
queObj.put("Name", name);
queObj.put("param", param);
}
} catch (JSONException jse) {
jse.printStackTrace();
}
}
}
//Now que array contains final merged data, convert it to ArrayList<Your_model>.
答案 1 :(得分:1)
制作课程
public class Data {
int id;
List<Que> que = new ArrayList<Que>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public List<Que> getQue() {
return que;
}
public void setQue(List<Que> que) {
this.que = que;
}
}
创建另一个名为Que
public class Que {
int RId;
int ViewId;
int Count;
public int getrId() {
return RId;
}
public void setrId(int rId) {
this.RId = rId;
}
public int getViewId() {
return ViewId;
}
public void setViewId(int viewId) {
this.ViewId = viewId;
}
public int getCount() {
return Count;
}
public void setCount(int count) {
this.Count = count;
}
}
使用gson
Gson gson = new Gson();
Data data = gson.fromJson(json, Data.class);
List<Que> queList = data.getQue();
for(Que que : queList){
System.out.println("This is R ID" +que.RId);
System.out.println("This is View ID" +que.ViewId);
System.out.println("This is Count" +que.Count);
确保您的json属性名称与java实例参数匹配。