0

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.

1
  • Consider using a Set rather than a Map. Commented May 21, 2015 at 10:09

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.