在Java对象中使用List转换JSON

时间:2016-02-20 03:31:50

标签: java json objectmapper

我试图在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"
}

1 个答案:

答案 0 :(得分:2)

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));