我已經拿到了JSON如下如何動態地從JSON字符串數組
{
"brands": [
{
"name": "ACC",
"quantity": "0",
"listedbrandID": 1,
"status": "0"
}
],
"others": [
{
"name": "dd",
"quantity": "55",
"listedbrandID": 1
},
{
"name": "dd",
"quantity": "55",
"listedbrandID": 1
}
]
}
我試圖從其他陣列中刪除dupcate JSON對象刪除重複的JSON對象
我是想它這個方式
String JSON = "{
"brands": [
{
"name": "ACC",
"quantity": "0",
"listedbrandID": 1,
"status": "0"
}
],
"others": [
{
"name": "dd",
"quantity": "55",
"listedbrandID": 1
},
{
"name": "dd",
"quantity": "55",
"listedbrandID": 1
}
]
}" ;
JSONObject json_obj = new JSONObject(json);
JSONArray array = json_obj.getJSONArray("others");
HashSet<Others> map = new HashSet<Others>();
for (int k = 0; k < array.length(); k++) {
Others otherbrands = new Others();
String name = array.getJSONObject(k).getString("name");
String quantity = array.getJSONObject(k).getString("quantity");
String listedbrandID = array.getJSONObject(k).getString("listedbrandID");
if(name!=null && !name.trim().equals(""))
{
otherbrands.setName(name);
otherbrands.setQuantity(quantity);
otherbrands.setListedbrandID(listedbrandID);
map.add(otherbrands);
}
}
for (int k = 0; k < array.length(); k++)
{
String name = array.getJSONObject(k).getString("name");
System.out.println(name);
if(!map.contains(name.trim()))
{
array.remove(k);
}
}
System.out.println(json_obj);
}
}
import java.util.Arrays;
public class Others {
private String name ;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
public String getListedbrandID() {
return listedbrandID;
}
public void setListedbrandID(String listedbrandID) {
this.listedbrandID = listedbrandID;
}
private String quantity ;
private String listedbrandID ;
@Override
public boolean equals (Object other)
{
if (!(other instanceof Others))
return false;
Others ob = (Others) other;
return name.equals(ob.name) &&
quantity.equals(ob.quantity);
}
@Override
public int hashCode()
{
return Arrays.hashCode(new String[]{quantity,name});
}
}
但其打印整個JSON
瞭解如何保持縮進一致 - 這使得該問題難以閱讀。 –
@AlexisC。那麼如何解決這個問題? – Pawan
爲什麼你在第一時間有if(!map.contains(name.trim()))?你的「地圖」是一個'HashSet',所以調用包含一個字符串是無意義的。 (順便說一句,它是一個非常糟糕的名字) –