Reputation: 32321
I have got the JSON as below
{
"brands": [
{
"name": "ACC",
"quantity": "0",
"listedbrandID": 1,
"status": "0"
}
],
"others": [
{
"name": "dd",
"quantity": "55"
},
{
"name": "dd",
"quantity": "55"
}
]
}
How can i remove the duplicates from others
JSON array
i have tried as following
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
String json = "{
"brands": [
{
"name": "ACC",
"quantity": "0",
"listedbrandID": 1,
"status": "0"
}
],
"others": [
{
"name": "dd",
"quantity": "55"
},
{
"name": "dd",
"quantity": "55"
}
]
}
";
JSONObject json_obj = new JSONObject(json);
JSONArray array = json_obj.getJSONArray("others");
HashMap<String, String> map = new HashMap<String, String>();
System.out.println(array.length());
for(int i=0;i<array.length();i++)
{
String name = array.getJSONObject(i).getString("name");
String quantity = array.getJSONObject(i).getString("quantity");
if(name!=null && !name.trim().equals(""))
{
map.put(name, quantity);
}
}
But no idea how to remove duplicate JSON other than which are present under Map only.
Upvotes: 0
Views: 5952
Reputation: 52185
Create an object representing your Others
. It will have a name
and quantity
property and it will also override the equals
method, wherein, two Other
objects are considered to be equal if they have the same name
and quantity
properties.
Once you have that, iterate over your JSON
, create a new Other
object and place it in a HashSet<Other>
. The .equals
will ensure that the HashSet
will contain unique items, as per your definition of unique.
Upvotes: 1