使用POJO循环行以创建缺少项的JSON

时间:2019-03-20 21:52:05

标签: java nested-loops

我在数据库中有以下几行:

ID    name   address1        address 2
-----------------------------------
123   Edvin  Hong Kong       Hong Kong
123   Edvin  Taipei          Taiwan
124   Advin  Bangkok         Thailand
-----------------------------------

我想要以下JSON结果:

"Item":[  
  {  "name": "Edvin"
     "addresses": [
        {
          "address1": "Hong Kong"
          "address2": "Hong Kong"
         } ,
        {
          "address1": "Taipei"
          "address2": "Taiwan"
        }
      ]
   },
   {  "name": "Advin"
     "addresses": [
        {
          "address1": "Bangkok"
          "address2": "Thaland"
         }
      ]
   }
]

我试图这样做:

List<Item> items= new ArrayList<Item>();
List<String> ids = new ArrayList<String>();

        for (Record record: records) { // Loop the rows show above
            if(!ids .contains(record.getId())) { //prevent duplicate Item
              Item item = new Item();
              item.setName(record.getSurname());
              Address address = new Address();
              address.setAddress1 = record.getAddress1();
              address.setAddress2 = record.getAddress2();
              item.setAddreses(address);
              items.add(item); // add the item into items
           }
           Ids.add(record.getId());
        }

上面的代码我只能获得商品名称埃德文的第一个地址我如何获得埃德文的第二个地址

1 个答案:

答案 0 :(得分:0)

首先,您创建的对象Item不适合您要获取的JSON。据我所知,对象Item具有类型为Addresses的属性,可以跟踪address1和address2,但是如果要上述JSON结果,则需要一个地址列表作为属性。

然后,如果要保留“列表项”和“列表ID”,并假设您正在收集所有具有相同名称的项,则代码应采用以下方式更改:

List<Item> items= new ArrayList<Item>();
List<String> ids = new ArrayList<String>();

    for (Record record: records) { // Loop the rows show above
        if(!ids .contains(record.getId())) { //prevent duplicate Item
          Item item = new Item();
          item.setName(record.getSurname());
          Address address = new Address();
          address.setAddress1 = record.getAddress1();
          address.setAddress2 = record.getAddress2();
          List<Address> addrList = new ArrayList<Address>();
          addrList.add(address);
          item.setAddreses(addrList);
          items.add(item); // add the item into items
       } else {
         for (Item it: items) {
            if(it.getName().equals(record.getSurname()) {
                 Address addr = new Address();
                 addr.setAddress1 = record.getAddress1();
                 addr.setAddress2 = record.getAddress2();
                 it.getAddresses().add(addr);
            }
         }
       }
       Ids.add(record.getId());
    }


确实不是最好的解决方案,在这种情况下,我建议您使用避免定义重复的Map,而不是使用List数据结构。