简体   繁体   中英

Converting a JSON with List in Java object

I am trying to convert the below JSON into a Java object using ObjectMapper class in jackson api but i am getting an error. How my java class should look like?

[{
    "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"
}]

If i have the below json i am able to convert it to java object.

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 support below method. Use them :)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM