使用GsonMap多个ndJson记录

pinkon5k  于 2022-12-13  发布在  其他
关注(0)|答案(1)|浏览(122)

我想用我的DTO类MapndJson中的多个记录。下面是我的ndJson文件:

// Record # 1 (This line is not included in the file and is only for clarification)
{
 "profile":{
      "salutation":"Mr",
      "title":null,
      "company":null
   }, 
   "phone":{
      "home_phone":null
   },
   "addresses":[
      {
         "address_id":"1",
         "title":"",
         "company":null,
         "salutation":null,
         "first_name":"Veronica",
         "last_name":"Costello",
         "second_name":null
      }
   ],
   "orders":{
      "placed_orders_count":2,
      "0":{
         "order_id":"000000001",
         "order_date":"2019-03-27 14:25:03"
      },
      "1":{
         "order_id":"000000002",
         "order_date":"2019-03-27 14:25:03"
      }
   },
   "customs":[
      
   ]
}

// Record # 2 (This line is not included in the file and is only for clarification)
{
    "profile":{
      "salutation":null,
      "title":null,
      "company":null,
      "job_title":null
   },
   "phone":{
      "home_phone":null,
      "business_phone":null,
      "mobile_phone":null,
      "fax_number":null
   },
   "addresses":[
      {
         "address_id":"2",
         "title":""
      }
   ],
   "orders":{
      "placed_orders_count":0
   },
   "customs":[
      
   ]
}

//Similarly the file has a lot of records

我想Map所有记录,但只能Map第一个记录。
我在How to Read ndJSON file in Java上问过类似的问题,但是我不能用接受的解决方案Map所有记录。下面是我的代码:

Gson gson = new Gson();
JsonReader reader = new JsonReader(new FileReader("customer.json"));
CustomerFeedDTO customerFeedDTO = gson.fromJson(reader, CustomerFeedDTO.class);

客户DTO类为:

private Map<String, ?> profile;
private Map<String, ?> phone;
private ArrayList<?> addresses;
private Map<String, ?> orders;
private ArrayList<?> customs;

// Getters and setter

但是我只得到了这个代码的第一条记录。我如何将所有的记录Map到CustomerDTO对象中?

nzk0hqpo

nzk0hqpo1#

您可以使用reader.peek()方法并在您的代码上应用循环,这样您就需要创建CustomerDTO的列表并不断在其中添加对象,例如:

List<CustomerFeedDTO> customerFeedDTOs = new ArrayList<CustomerFeedDTO>();
Gson gson = new Gson();
JsonReader reader = new JsonReader(new FileReader("customer.json"));
// Required
reader.setLenient(true);
while (reader.peek() != JsonToken.END_DOCUMENT) {
    CustomerFeedDTO customerFeedDTO = gson.fromJson(reader, CustomerFeedDTO.class);
    customerFeedDTOs.add(customerFeedDTO);
}

Note that读取器也有一个hasNext()方法,但是当你到达文档末尾时会出现异常。

相关问题