我正在尝试使用 jackson api 中的 ObjectMapper 类将下面的 JSON 转换为 Java 对象,但出现错误。 我的 java 类应该是什么样子?
[{
"saleValue": 100,
"priceEventTypeCode": 1,
"startDate": "2016-03-23T18:00:00.0Z",
"updateStoredValue": true,
"autoRound": false,
"priceChangeNumber": "tkt"
},
{
"saleValue": 100,
"priceEventTypeCode": 1,
"startDate": "2016-03-23T18:00:00.0Z",
"updateStoredValue": true,
"autoRound": false,
"priceChangeNumber": "tkt"
}]
如果我有下面的 json,我可以将其转换为 java 对象。
public class Pid
{
private String priceChangeNumber;
private String startDate;
private String autoRound;
private String priceEventTypeCode;
private String saleValue;
private String updateStoredValue;
// getter and setter functions removed here.
}
Json:
{
"saleValue": 100,
"priceEventTypeCode": 1,
"startDate": "2016-03-23T18:00:00.0Z",
"updateStoredValue": true,
"autoRound": false,
"priceChangeNumber": "tkt"
}
最佳答案
ObjectMapper 支持以下方法。使用它们:)
//To Array
Pid[] pidArray = mapper.readValue(json, Pid[].class);
//To List
List<Pid> pidList1 = mapper.readValue(json, new TypeReference<List<Pid>>(){});
//To List Another way
List<Pid> pidList2 = mapper.readValue(json, mapper.getTypeFactory().constructCollectionType(List.class, Pid.class));
关于java - 将 JSON 与 Java 对象中的 List 转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35518794/