Jackson with Spring WebFlux

Viewed 44

Json:

{
    "response": {
        "count": 3,
        "items": [
            6651536,
            20410167,
            40345521
        ]
    }
}

NOT WORK - FriendsDTO:

@Jacksonized
@Builder
@Value
public class FriendsDTO {

    int count;

    @JsonProperty("items")
    List<Integer> friends;

}

WORK - FriendsDTO:

@Jacksonized
@Builder
@Value
public class FriendsDTO {

    Response response;
    
    @Jacksonized
    @Builder
    @Value
    public static class Response {

        int count;

        @JsonProperty("items")
        List<Integer> friends;

    }

}

WebFluxClient request:

FriendsDTO friends = webFluxClient.get()
     .uri(config.methodGetFriends(), builder -> {
           builder.queryParam("access_token", accessToken);
           builder.queryParam("v", config.version());
           return builder.build();
      })
     .accept(MediaType.APPLICATION_JSON)
     .retrieve()
     .bodyToMono(FriendsDTO.class)
     .log()
     .block();
logger.info(friends.toString());

output WORK: FriendsDTO(response=FriendsDTO.Response(count=3, friends=[6651536, 20410167, 40345521]))

output NOT WORK: FriendsDTO(count=0, friends=null)

How can I get rid of this misunderstanding in the Response view for successful json parsing ?

1 Answers

Thats the expected behaviour

{
  name  : "name",
 description : "description"
}

This can be written as

class <ClassName>{
 private String name;
 private String description;
}

The json does not carry the ClassName. Similarly in your case, the word Response should be a valid attribute, like how I defined name in this example.

So , if you want , this class to work

@Jacksonized
@Builder
@Value
public class FriendsDTO {

    int count;

    @JsonProperty("items")
    List<Integer> friends;

}

You JSON should be changed from

{
    "response": {
        "count": 3,
        "items": [
            6651536,
            20410167,
            40345521
        ]
    }
}

To

  {
            "count": 3,
            "items": [
                6651536,
                20410167,
                40345521
            ]
        }
Related