使用java将jsonobject添加到jsonaray中时避免重复



我有一个对象列表,正在转换为JSONArray。正在对JSONObject进行迭代,并生成一个JSONObject数组。

现在,我想避免重复的对象插入到JSONArray中。

请在下面找到我的java代码。

JSONArray responseArray1 = new JSONArray();
if (!itemList.isEmpty())
{
jsonArray = new JSONArray(itemList);
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject jsonObj = jsonArray.getJSONObject(i);
JSONObject responseObj = new JSONObject();
String attr_label = jsonObj.optString("attr_label");
if(StringUtils.equalsIgnoreCase(attr_label, "long_description")) {
long_description = jsonObj.optString("value");
}
else if(StringUtils.equalsIgnoreCase(attr_label, "description")) {
description = jsonObj.optString("value");
}
responseObj.put("id", jsonObj.opt("id")); // i will get duplicate id
responseObj.put("code", jsonObj.opt("code")); // i will get duplicate code
responseObj.put("long_description", long_description);
responseObj.put("description", description);
responseArray1.put(responseObj);
}
}

请找到我实际的jsonArray:

[  
{  
"code":"xyaz",
"attr_label":"long_description",
"id":"12717",
"value":"Command Module"
},
{  
"code":"xyaz",
"attr_label":"description",
"id":"12717",
"value":"Set Point Adjustment"
},
]

我期待着像下面这样的jsonArray:

[  
{  
"code":"xyaz",
"id":"12717",
"long_description":"Command Module"
"description" : "Set Point Adjustment"
}
]

更新:

我已经尝试使用以下代码来避免重复插入id&code字段。但工作不正常。它的插入也重复。

List<String> dummyList=new ArrayList<String>();
JSONArray responseArray2 = new JSONArray(itemList);
if (!itemList.isEmpty())
{
jsonArray = new JSONArray(itemList);
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject jsonObj = jsonArray.getJSONObject(i);
JSONObject responseObj = new JSONObject();
String itemCode = jsonObj.optString("code");
String id = jsonObj.optString("id");
if(!dummyList.contains(itemCode) && !dummyList.contains(id) ) {
dummyList.add(String.valueOf(jsonObj.opt("id")));
dummyList.add(String.valueOf(jsonObj.opt("code")));
responseObj.put("id", jsonObj.opt("id"));
responseObj.put("code", jsonObj.opt("code"));
responseObj.put("long_description", long_description);
responseObj.put("description", description);
responseArray2.put(responseObj);
}
}
}

制作一个临时数组列表,并在该arrayList中添加唯一代码,检查它是否已经存在于arrayList中,然后不要再放这个

String code = jsonObj.opt("code");
if(!arrayList.contains(code))
{
arrayList.add(code);
responseObj.put("id", jsonObj.opt("id")); 
responseObj.put("code", jsonObj.opt("code")); 
responseObj.put("long_description", long_description);
responseObj.put("description", description);
}

使用TreeSet并将Comparator添加到它们的构造函数中,在该构造函数中比较对象的重复数据。例如:-

Set<Sample> sampleSet=new TreeSet<>(new Sample());

其中示例类看起来像:-

class Sample implements Camparator<Sample>{
private String name;
private String id;
//getter 
//setter
@Override
public String compare(Sample o1,Sample o2){
return o1.getName.compareTo(o2.getName);
}
}

这将提供一组唯一的名称条目。

最新更新