0

I have a JSONArray which consist of set of JSONObjects in it. What is the best algorithm to get unique JSONObjects from

"lessaon_plan_data": [
      {
        "lessonplan_marks": 100,
        "lessonplan_name": "wdwd",
        "lessonplan_subject": "Maths"
      },
      {
        "lessonplan_marks": 50,
        "lessonplan_name": "ewewd",
        "lessonplan_subject": "Maths"
      },
      {
        "lessonplan_marks": 8,
        "lessonplan_name": "qwefqwef",
        "lessonplan_subject": "Maths"
      },
      {
        "lessonplan_marks": 20,
        "lessonplan_name": "qwefqwef",
        "lessonplan_subject": "Maths"
      },
      {
        "lessonplan_marks": 4,
        "lessonplan_name": "qwefqwef",
        "lessonplan_subject": "Maths"
      },
      {
        "lessonplan_marks": 8,
        "lessonplan_name": "qwefqwef",
        "lessonplan_subject": "Maths"
      },
      {
        "lessonplan_marks": 20,
        "lessonplan_name": "qwefqwef",
        "lessonplan_subject": "Maths"
      },
      {
        "lessonplan_marks": 4,
        "lessonplan_name": "qwefqwef",
        "lessonplan_subject": "Maths"
      },
      {
        "lessonplan_marks": 8,
        "lessonplan_name": "qwefqwef",
        "lessonplan_subject": "Maths"
      }
    ]

What I have tried is this:

private JSONArray removeDuplicate(JSONArray rubricReportArray) {
    Log.e("MethodEntered", "success");
    JSONArray tempArray = new JSONArray();
    try {
        JSONObject tempStudentObj = null;
        for (int i = 0; i < rubricReportArray.length(); i++) {
            JSONObject studentObj = rubricReportArray.getJSONObject(i);


            tempStudentObj = new JSONObject();
            tempStudentObj.put("student_name", studentObj.getString("student_name"));
            tempStudentObj.put("lessonplan_name", studentObj.getString("lessonplan_name"));
            tempStudentObj.put("student_id", studentObj.getString("student_id"));
            tempStudentObj.put("lessonplan_subject", studentObj.getString("lessonplan_subject"));
            tempStudentObj.put("student_marks", studentObj.getString("student_marks"));
            tempStudentObj.put("lessonplan_class", studentObj.getString("lessonplan_class"));


            JSONArray duplicateArray = studentObj.getJSONArray("lessaon_plan_data");
            JSONArray uniqueArray = new JSONArray();
            Map<String,String> uniqueMap = new HashMap<>();

            for (int j = 0; j < duplicateArray.length(); j++) {
                boolean flag = false;
                String lessonMarks = duplicateArray.getJSONObject(j).getString("lessonplan_marks");
                String lessonName = duplicateArray.getJSONObject(j).getString("lessonplan_name");
                String lessonSubject = duplicateArray.getJSONObject(j).getString("lessonplan_subject");
                for (int k = j + 1; k < duplicateArray.length() - 1; k++) {
                    String currentLessonMarks = duplicateArray.getJSONObject(k).getString("lessonplan_marks");
                    String currentLessonName = duplicateArray.getJSONObject(k).getString("lessonplan_name");
                    String currentLessonSubject = duplicateArray.getJSONObject(k).getString("lessonplan_subject");
                    if (!lessonSubject.equalsIgnoreCase(currentLessonSubject)) {
                        uniqueArray.put(duplicateArray.getJSONObject(j));
                        break;
                    } else if (!lessonName.equalsIgnoreCase(currentLessonName)) {
                        flag = false;
                        uniqueArray.put(duplicateArray.getJSONObject(j));
                        break;
                    } else {
                        if (!lessonMarks.equalsIgnoreCase(currentLessonMarks)) {
                            flag = true;
                        }
                    }
                }
                if (flag) {
                    uniqueArray.put(duplicateArray.getJSONObject(j));
                }
                //Log.e("Unique JSON",set.toString());
            }
            tempStudentObj.put("lessaon_plan_data", uniqueArray);
            Log.e("TempStudent", tempStudentObj.toString());
            tempArray.put(tempStudentObj);

        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return tempArray; //assign temp to original

}

I am getting unique objects where there is unique subject and lessons. But when there are same lessons and same subjects but the score differs then problem comes.

How to get unique JSONObjects from it and store it in a new or replace in the same JSONArray? I have tried most of the solutions which is in stackoverflow. But nothing worked in my condition. Please help. Thanks in advance

3
  • Show your code, what have you done? Commented Nov 7, 2016 at 13:05
  • I update the question please check. Commented Nov 7, 2016 at 13:09
  • corrected your code and posted as an answer. please check Commented Nov 7, 2016 at 13:59

2 Answers 2

1

It is not really clear what you have done or how you are storing the objects.

But if you haven't already then my suggestion is to use a Java collection which only maintains unique objects, and not an array.

So a HashSet, TreeSet or something similar. Then you can either;

  1. Prior to insertion, check the collection if the object exists prior to inserting, and then handle it as you require.
  2. Insert and replace an existing object with the new object

Remember that the comparison of objects will require you to create your own equals() comparison in the Class (and of course you will also need to override hashcode())

See also: Prevent duplicate entries in arraylist

Update:

I used Gson to decode my json and the following only gave me 3 unique entries;

Gson gson = new Gson();
Type listType = new TypeToken<HashSet<LessonPlan>>(){}.getType();
Set<LessonPlan> lpList = new Gson().fromJson(json, listType);

The lessonplan class

public class LessonPlan {
    private int lessonplan_marks;
    private String lessonplan_name;
    private String lessonplan_subject;

    public int getLessonplan_marks() {
        return lessonplan_marks;
    }

    public void setLessonplan_marks(int lessonplan_marks) {
        this.lessonplan_marks = lessonplan_marks;
    }

    public String getLessonplan_name() {
        return lessonplan_name;
    }

    public void setLessonplan_name(String lessonplan_name) {
        this.lessonplan_name = lessonplan_name;
    }

    public String getLessonplan_subject() {
        return lessonplan_subject;
    }

    public void setLessonplan_subject(String lessonplan_subject) {
        this.lessonplan_subject = lessonplan_subject;
    }

    public LessonPlan() {


    }

    public String toString()
    {
        return "Name: " + this.getLessonplan_name() + " subject: " + this.getLessonplan_subject() + " marks: " + this.getLessonplan_marks();
    }


    public boolean equals(Object obj)
    {
        if (obj instanceof LessonPlan)
        {
            LessonPlan other = (LessonPlan)obj;
            if (other.getLessonplan_name().equals(this.getLessonplan_name()) && other.getLessonplan_subject().equals(this.getLessonplan_subject()))
                return true;
            else
                return false;
        }
        else
            return false;
    }

    public int hashCode()
    {
        return this.getLessonplan_name().hashCode() + this.getLessonplan_subject().hashCode();
    }

Of course doing it this way I have no control of which of the objects is kept.

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

4 Comments

I have updated the question with what i have tried. I just want to remove duplicate JSONObjects thats it. all the property in the JSONObject should be unique
I still think that dealing with Java collections is a better way to do this. Convert from JSON to obecjst, find and remove duplicates, and then convert back to JSON.
Still no success.
I really appreciate your efforts..but i got my solution. Even I will give it a try. Thank you so much for the help
0
private JSONArray removeDuplicate(JSONArray rubricReportArray) throws Exception{
        Log.e("MethodEntered", "success");
        JSONArray tempArray = new JSONArray();
        try {
            JSONObject tempStudentObj = null;
            for (int i = 0; i < rubricReportArray.length(); i++) {
                JSONObject studentObj = rubricReportArray.getJSONObject(i);


                tempStudentObj = new JSONObject();
                tempStudentObj.put("student_name", studentObj.getString("student_name"));
                tempStudentObj.put("lessonplan_name", studentObj.getString("lessonplan_name"));
                tempStudentObj.put("student_id", studentObj.getString("student_id"));
                tempStudentObj.put("lessonplan_subject", studentObj.getString("lessonplan_subject"));
                tempStudentObj.put("student_marks", studentObj.getString("student_marks"));
                tempStudentObj.put("lessonplan_class", studentObj.getString("lessonplan_class"));


                JSONArray duplicateArray = studentObj.getJSONArray("lessaon_plan_data");
                JSONArray uniqueArray = new JSONArray();
                int k;
                for (int j = 0; j < duplicateArray.length(); j++) {
                    boolean flag = false;
                    String lessonMarks = duplicateArray.getJSONObject(j).getString("lessonplan_marks");
                    String lessonName = duplicateArray.getJSONObject(j).getString("lessonplan_name");
                    String lessonSubject = duplicateArray.getJSONObject(j).getString("lessonplan_subject");
                    for (k = j + 1; k < duplicateArray.length() - 1; k++) {

                        String currentLessonMarks = duplicateArray.getJSONObject(k).getString("lessonplan_marks");
                        String currentLessonName = duplicateArray.getJSONObject(k).getString("lessonplan_name");
                        String currentLessonSubject = duplicateArray.getJSONObject(k).getString("lessonplan_subject");

                        if (lessonMarks.equalsIgnoreCase(currentLessonMarks) && (lessonSubject.equalsIgnoreCase(currentLessonSubject) &&
                                lessonName.equalsIgnoreCase(currentLessonName) 
                               ){
                            break;
                        }


                    }
                    if (k == duplicateArray.length() - 1){
                        uniqueArray.put(duplicateArray.getJSONObject(j));
                    }
                }
                tempStudentObj.put("lessaon_plan_data", uniqueArray);
                Log.e("TempStudent", tempStudentObj.toString());
                tempArray.put(tempStudentObj);

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return tempArray; //assign temp to original

    }

Reference:- for basic algo behind finding unique elements from an array http://www.techcrashcourse.com/2015/08/c-program-print-unique-elements-unsorted-array.html

5 Comments

I tried but it didn't worked out. and 'k' is not even in the scope. you have checked the condition outside the for loop. and the "if" condition inside the for loop will always break because all the subjects are maths here.
Edited my answer, check complete code. Even if subject is same, name and marks are different. code will check for all three values to be unique.
Your solution is working for this set of of test case only. When there is only one JSONObject or 2 JSONObjects then it not working correctly. Please help.
Please check this link techcrashcourse.com/2015/08/… and debug your program too. The solution given on link works for all arrays (even if array size is 2).
Great it worked out. Actually a little change was required in your code and it ran correctly for every conditions. Thanks again mate for a quick reply. Saved my day.

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.