代码之家  ›  专栏  ›  技术社区  ›  J.TrLu

如何比较同一JSONObject中的条目

  •  0
  • J.TrLu  · 技术社区  · 6 年前

       {"ORDER_1": {"FNAME" : "JOHN","LNAME" : "B","ORDER_ID" : "D123"},
        "ORDER_2": {"FNAME" : "LAURA","LNAME" : "S","ORDER_ID" : "D456"},
        "ORDER_3": {"FNAME" : "JACK","LNAME" : "H","ORDER_ID" : "D123"}}
    

    下面是我动态收集客户信息并将其放入JSONObject散列集中的代码

        Set<JSONObject> customerCollection = new HashSet<JSONObject>();
        Iterator<String> keys = (Iterator<String>) customerOrders.keys();
        while (keys.hasNext()) {
            String key = keys.next();
            JSONObject obj = customerOrders.getJSONObject(key);
    
            JSONObject result = new JSONObject();
            JSONArray customerList = new JSONArray();
    
            JSONObject customer = new JSONObject();
            JSONObject customerObj = new JSONObject();
    
            customer.put("FNAME", obj.optString("FNAME"));
            customer.put("LNAME", obj.optString("LNAME"));
            customerObj.put("customer", customer);
            customerList.add(customerObj);
            result.put("customers", customerList);
    
            customerCollection.add(result);
        }
    

    [{"customers": [{"name": {"fname": "JOHN","lname": "B"}}]},
     {"customers": [{"name": {"fname": "LAURA","lname": "S"}}]},
     {"customers": [{"name": {"fname": "JACK","lname": "H"}}]}]
    

    现在有一个要求,那就是将共享同一个订单ID的客户分组,而这正是我有点挣扎的地方。如何比较同一个JSONObject的条目,并根据ORDER\u ID键值将它们组合在一起?所以最终的输出应该是这样的(注意到客户JOHN和JACK现在处于相同的JSONArray中,因为他们共享相同的订单ID)

    [
        {
         "customers": [{"name": {"fname": "JOHN","lname": "B"}},
                       {"name": {"fname": "JACK","lname": "H"}}
                      ]
        },
        {"customers": [{"name": {"fname": "LAURA","lname": "S"}}
    ]
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   John Czukkermann    6 年前

    逻辑的问题在于,您使用一个循环,为每个客户条目保存客户,而不是为每个订单保存一次。

    为此,创建一个映射,该映射使用ORDER\u ID作为每个条目的键,并使用一个客户数组作为其值。

    我意识到stackoverflow希望我把答案编码并发布出来,但我认为这样做(对我)没有效果。