0

I have a json array having four objects.

{"name":"Ram", "email":"ram@gmail.com", "age":23}, 
{"name":"Shyam", "email":"shyam23@gmail.com", "age":28},  
{"name":"John", "email":"john@gmail.com", "age":23},    
{"name":"Bob", "email":"bob32@gmail.com", "age":41}   

I want to iterate through the json objects and display the details of the persons having same age. I am using Java. I am new to json.Can anyone suggest how to proceed. I am using json.org library.

I have came this far:

public static void main(String[] args) {
    String text="{\"name\":\"Ram\", \"email\":\"ram@gmail.com\", \"age\":23}"
            + "{\"name\":\"Shyam\", \"email\":\"shyam23@gmail.com\", \"age\":28}"
            + "{\"name\":\"John\", \"email\":\"john@gmail.com\", \"age\":23}"
            + "{\"name\":\"Bob\", \"email\":\"bob32@gmail.com\", \"age\":41}";
    String changed=text.toString();
    int pos=changed.lastIndexOf("}");
    String change=changed.substring(0,pos );
    change=change.replace("}", "},");
    String res=change.concat("}"); 
    String msg="["+res+"]";
    JSONArray json=new JSONArray(msg);
    for(int i=0;i<json.length();i++){
        JSONObject obj= json.getJSONObject(i);
    }
}
Robin Topper
  • 2,295
  • 1
  • 17
  • 25
Amit
  • 41
  • 1
  • 6
  • Possible duplicate of [Parse JSON with org.json](https://stackoverflow.com/questions/6442347/parse-json-with-org-json) – Robin Topper Aug 03 '17 at 10:05
  • 2
    What have you tried so far? Please show us some code. Also your json isn't valid. Check it here: https://jsonlint.com/ – JanTheGun Aug 03 '17 at 10:06
  • I have parsed the array to get each object. What I want to know is how to proceed in this situation, I will use a valid json but I cant understand how to traverse the whole json array and compare different age values . I have came this far: – Amit Aug 03 '17 at 10:13
  • Edit your question to add this code, and format it properly. – Asew Aug 03 '17 at 10:16
  • @JanTheGun can u help? – Amit Aug 03 '17 at 10:37

3 Answers3

1

This question actually contains 2 parts:

  1. How to properly parse JSON? There quite a lot out there, e.g. Gson, Jackson or JsonP... and also you have options whether to parse json into general Json object or to a specific POJO. Create a POJO class to parse it can ease the step #2.
  2. To process "display the details of the persons having same age", I would recommend using Java8's stream feature to do it, just by a line of Code.

    List<Person> people = parseJson(text); // depend on which lib you choose.
    // Group person by age.
    Map<Int, List<Person>> peobleByAge = people.stream().collect(Collectors.groupingBy(Person::getAge));
    
Duong Nguyen
  • 830
  • 6
  • 10
1
public class JSONThing {

    public void change() {

        String text = "{\"name\":\"Ram\", \"email\":\"ram@gmail.com\", \"age\":23}"
            + "{\"name\":\"Shyam\", \"email\":\"shyam23@gmail.com\", \"age\":28}"
            + "{\"name\":\"John\", \"email\":\"john@gmail.com\", \"age\":23}"
            + "{\"name\":\"Bob\", \"email\":\"bob32@gmail.com\", \"age\":41}";
        String changed = text.toString();
        int pos = changed.lastIndexOf("}");
        String change = changed.substring(0, pos);
        change = change.replace("}", "},");
        String res = change.concat("}");
        String msg = "[" + res + "]";
        JSONArray json;
        try {
            json = new JSONArray(msg);
            Map<Integer, List<JSONObject>> mapp = new HashMap<>();
                for (int i = 0; i < json.length(); i++) {
                    JSONObject obj = json.getJSONObject(i);
                    List<JSONObject> list = mapp.getOrDefault(obj.getInt("age"),new ArrayList<>());
                    list.add(obj);
                    mapp.put(obj.getInt("age"),list);
            }

        System.out.println(mapp);
        for (Entry<Integer, List<JSONObject>> entry : mapp.entrySet())
        {
          ListIterator<JSONObject> i=entry.getValue().listIterator();
          System.out.println(entry.getKey());
            //System.out.println(entry.getKey() + "/" + entry.getValue());
          while(i.hasNext()){
              System.out.println(i.next());
          }
        }

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

public static void main(String[] args) {
    JSONThing j  = new JSONThing();
    j.change();
}

}

implememt this, It will print all the users having same age.

theGamblerRises
  • 686
  • 1
  • 11
  • 27
0

There are in fact a lot of questions in your question ;-)

First of all I said your json is not valid. The brackets are missing and also some commas.

I would store the data in a simple java object first. So let's create a Person class and implement our own toString-Method.

public class Person {
    String name;
    String email;
    int age;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }

    public String toString(){
        String output = "Name: " + this.name + "\n";
        output += "Email: " + this.email + "\n";
        output += "Age: " + this.age + "\n\n";
        return output;
    }

}

Then you can iterate through the json array, create a Person object in each iteration and fill it with the data. Also in each iteration we will put that Person object into a map with the 'age' as key.

The result is a Map that has the age as key and a list of persons as values. You can iterate through them now (as I did here) or you can access the lists directly via the age-key.

public static void main(String[] args) {
        String text = "[{\"name\": \"Ram\",\"email\": \"ram@gmail.com\",\"age\": 23}, {\"name\": \"Shyam\",\"email\": \"shyam23@gmail.com\",\"age\": 28}, {\"name\": \"John\",\"email\": \"john@gmail.com\",\"age\": 23}, {\"name\": \"Bob\",\"email\": \"bob32@gmail.com\",\"age\": 41}]";
        JSONArray jsonArr = new JSONArray(text);

        Map<Integer, List<Person>> ageMap = new HashMap<Integer, List<Person>>();
        for (int i = 0; i < jsonArr.length(); i++) {
            JSONObject obj = (JSONObject) jsonArr.get(i);
            Person person = new Person();
            person.setName(obj.getString("name"));
            person.setEmail(obj.getString("email"));
            person.setAge(obj.getInt("age"));

            int age = person.getAge();
            List<Person> ageList = ageMap.get(age);
            if (ageList == null) {
                ageList = new ArrayList<Person>();
            }

            ageList.add(person);
            ageMap.put(age, ageList);

        }

        for (Map.Entry<Integer, List<Person>> entry : ageMap.entrySet()) {
            List<Person> ageList = entry.getValue();
            if (ageList.size() > 1) {
                System.out.println("*****************************");
                System.out.println("Person with same age '" + entry.getKey() + "':" + "\n");

                for (Person person : ageList) {
                    System.out.println(person.toString());
                }
                System.out.println("\n");
            }

        }

    }

Of course this is not the only way to do that and I'm sure that this can be done in a more efficient way.

JanTheGun
  • 2,165
  • 17
  • 25