我想用我的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
对象中?
1条答案
按热度按时间nzk0hqpo1#
您可以使用
reader.peek()
方法并在您的代码上应用循环,这样您就需要创建CustomerDTO
的列表并不断在其中添加对象,例如:Note that
读取器也有一个hasNext()
方法,但是当你到达文档末尾时会出现异常。