Deserialize a json array to objects using Jackson and WebClient

前端 未结 3 1757
失恋的感觉
失恋的感觉 2020-12-31 02:53

I have a problem during the deserialization of a json array using Spring. I have this json response from a service:

[
    {
        \"symbol\": \"XRPETH\",
          


        
相关标签:
3条回答
  • 2020-12-31 03:13

    Your response is simply List<AccountOrder>. But, your POJO has wrapped List<AccountOrder>. So, according to your POJO, your JSON should be

    {
      "accountOrders": [
        {
    

    But, you are JSON is

    [
        {
           "symbol": "XRPETH",
           "orderId": 12122,
            ....
    

    So, there is mismatch and failing the deserialization. You need to change to

    bodyToMono(AccountOrder[].class)
    
    0 讨论(0)
  • 2020-12-31 03:15

    Regarding your updated answer to your question, using bodyToFlux is unnecessarily inefficient and semantically doesn't make much sense either as you don't really want a stream of orders. What you want is simply to be able to parse the response as a list.

    bodyToMono(List<AccountOrder>.class) won't work due to type erasure. You need to be able to retain the type at runtime, and Spring provides ParameterizedTypeReference for that:

    bodyToMono(new ParameterizedTypeReference<List<AccountOrder>>() {})
    
    0 讨论(0)
  • 2020-12-31 03:28

    For the response to be matched with AccountOrderList class, json has to be like this

    {
      "accountOrders": [
        {
            "symbol": "XRPETH",
            "orderId": 12122,
            "clientOrderId": "xxx",
            "price": "0.00000000",
            "origQty": "25.00000000",
            "executedQty": "25.00000000",
            "status": "FILLED",
            "timeInForce": "GTC",
            "type": "MARKET",
            "side": "BUY",
            "stopPrice": "0.00000000",
            "icebergQty": "0.00000000",
            "time": 1514558190255,
            "isWorking": true
        },
        {
            "symbol": "XRPETH",
            "orderId": 1212,
            "clientOrderId": "xxx",
            "price": "0.00280000",
            "origQty": "24.00000000",
            "executedQty": "24.00000000",
            "status": "FILLED",
            "timeInForce": "GTC",
            "type": "LIMIT",
            "side": "SELL",
            "stopPrice": "0.00000000",
            "icebergQty": "0.00000000",
            "time": 1514640491287,
            "isWorking": true
        },
        ....
    ]
    }
    

    This is what the error message says "out of START_ARRAY token"

    If you cannot change the response, then change your code to accept Array like this

    this.webClient.get().uri(payload).accept(MediaType.APPLICATION_JSON)
                            .retrieve().bodyToMono(AccountOrder[].class).log();
    

    You can convert this array to List and then return.

    0 讨论(0)
提交回复
热议问题