2017-08-03 53 views
0

我有一個json數組有四個對象。Comapring Json Array的對象並顯示具有相同參數的對象

{"name":"Ram", "email":"[email protected]", "age":23}, 
{"name":"Shyam", "email":"[email protected]", "age":28}, 
{"name":"John", "email":"[email protected]", "age":23},  
{"name":"Bob", "email":"[email protected]", "age":41} 

我想遍歷json對象並顯示具有相同年齡的人的詳細信息。我正在使用Java。 我是json的新手。任何人都可以提出如何繼續。我正在使用json.org庫。

我已經來到這麼遠:

public static void main(String[] args) { 
    String text="{\"name\":\"Ram\", \"email\":\"[email protected]\", \"age\":23}" 
      + "{\"name\":\"Shyam\", \"email\":\"[email protected]\", \"age\":28}" 
      + "{\"name\":\"John\", \"email\":\"[email protected]\", \"age\":23}" 
      + "{\"name\":\"Bob\", \"email\":\"[email protected]\", \"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); 
    } 
} 
+0

[Parse JSON with org.json]的可能重複(https://stackoverflow.com/questions/6442347/parse-json-with-org-json) –

+2

你到目前爲止嘗試過什麼?請給我們看一些代碼。你的json也是無效的。檢查它在這裏:https://jsonlint.com/ – JanTheGun

+0

我已經解析了數組來獲取每個對象。我想知道的是如何在這種情況下進行,我將使用有效的json,但我無法理解如何遍歷整個json數組並比較不同的年齡值。我來了這麼遠: – Amit

回答

1

這個問題實際上包含兩個部分:

  1. 如何正確地解析JSON?那裏有很多,例如Gson,Jackson或JsonP ......並且你也可以選擇是否將JSON解析爲一般的Json對象或特定的POJO。創建一個POJO類來解析它可以緩解第2步。
  2. 要處理「顯示同齡人的細節」,我會建議使用Java8的流功能來完成它,只需通過一行代碼即可。

    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)); 
    
1
public class JSONThing { 

    public void change() { 

     String text = "{\"name\":\"Ram\", \"email\":\"[email protected]\", \"age\":23}" 
      + "{\"name\":\"Shyam\", \"email\":\"[email protected]\", \"age\":28}" 
      + "{\"name\":\"John\", \"email\":\"[email protected]\", \"age\":23}" 
      + "{\"name\":\"Bob\", \"email\":\"[email protected]\", \"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這一點,就會打印所有具有相同年齡的用戶。

0

其實有很多你的問題;-)

,首先的問題,我說你JSON是無效的。括號丟失,也有一些逗號。

我會先將數據存儲在一個簡單的java對象中。所以我們來創建一個Person類並實現我們自己的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; 
    } 

} 

然後你可以遍歷json數組,在每次迭代中創建一個Person對象,並用數據填充它。同樣在每次迭代中,我們都會將該Person對象放入一個以'年齡'爲關鍵字的地圖中。

結果是一個以年齡作爲關鍵字和人員列表作爲值的地圖。你現在可以迭代它們(就像我在這裏做的那樣),或者你可以直接通過age-key來訪問列表。

public static void main(String[] args) { 
     String text = "[{\"name\": \"Ram\",\"email\": \"[email protected]\",\"age\": 23}, {\"name\": \"Shyam\",\"email\": \"[email protected]\",\"age\": 28}, {\"name\": \"John\",\"email\": \"[email protected]\",\"age\": 23}, {\"name\": \"Bob\",\"email\": \"[email protected]\",\"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"); 
      } 

     } 

    } 

當然,這不是唯一的方法,我相信這可以以更有效的方式完成。