J
J
Jake Taylor2021-11-16 20:35:14
JSON
Jake Taylor, 2021-11-16 20:35:14

Why does HATEOAS + @JsonView return an empty object?

There is an object with a certain set of fields c @JsonView:

public class OrderDto extends AbstractDto<OrderDto> {
    @Valid
    private UserDto user;

    @Valid
    private GiftCertificateDto giftCertificate;

    @JsonView(View.FindOrderForUser.class)
    private BigDecimal price;

    @JsonView(View.FindOrderForUser.class)
    private LocalDateTime purchaseDate;
}


Why do I get a void when returning this object OrderDtoin the controller along with links HATEOASin response:

@GetMapping(UrlMapping.ORDER_USER)
    @JsonView(View.FindOrderForUser.class)
    public EntityModel<OrderDto> findOrderForUser(@PathVariable long userId, @PathVariable long orderId) {
        OrderDto orderDto = orderService.findOrderForUser(orderId, userId);
        return EntityModel.of(orderDto);
    }


Result:

{}

But if I return a simple object OrderDto, then everything works and only the annotated @JsonViewfields are displayed:

@GetMapping(UrlMapping.ORDER_USER)
@JsonView(View.FindOrderForUser.class)
public OrderDto findOrderForUser(@PathVariable long userId, @PathVariable long orderId) {
    return orderService.findOrderForUser(orderId, userId);
}


Result:
{
    "createDate": "2021-06-25T21:38:01",
    "lastUpdateDate": "2021-05-21T17:19:06"
}


But in this case, you need HATEOASlinks to be present and the result is like this:

{
    "price": 1.00,
    "purchaseDate": "2021-11-15T10:38:45.193",

    "_links": {
        "self": {
            "href": "http://localhost:8080/orders/1"
        }
    }


Also in application.properties, I set the property spring.jackson.mapper.default-view-inclusion=true, but the controller method, in this situation, returned all the fields of the OrderDto object.

@JsonIgnore- not a solution, because sometimes I need to output as JSON all the fields of the OrderDto object, and in some situations, like this, not all fields.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question