【问题标题】:Java Jackson serialization handle on getter throws exception [duplicate]getter上的Java Jackson序列化句柄抛出异常[重复]
【发布时间】:2017-12-13 10:36:49
【问题描述】:

我使用具有方法的外部库:

public class CustomUserDetails implements UserDetails {

    private final User principal;
    private final Collection<GrantedAuthority> authorities;

    //constructor, getters, setters

    @Override
    public String getPassword() {
        throw new UnsupportedOperationException("Not allowed");
    }
}

我有一个返回该对象实例的@RequestMapping:

@RequestMapping(value = "/authorities", method = GET)
    public ResponseEntity getAuthorities() {
        return new ResponseEntity<>(authenticatedUser.getAuthentication(), HttpStatus.OK); //getAuthentication returns CustomUserDetails instance
    }

我得到了 org.springframework.http.converter.HttpMessageNotWritableException: Could not write content: Not allowed.

我该如何处理? Ingore 或为此属性设置一些默认值。

UPD我无法将 @JsonIngore 添加到该类,因为它不是我的库,我无权访问它的源代码。

【问题讨论】:

  • @EbrahimPoursadeqi 这个帖子如何解决我的问题??
  • 使用 Jackson mixins 来克服 3rd 方的限制。
  • 我添加了一个重复的链接。
  • @SotiriosDelimanolis 谢谢。我已经成功了)

标签: java json spring-mvc jackson


【解决方案1】:

您可以在getPassword() 方法之上编写JsonIgnore 注释。这样您就可以告诉Jackon 不要尝试对该字段进行序列化

https://fasterxml.github.io/jackson-annotations/javadoc/2.4/com/fasterxml/jackson/annotation/JsonIgnore.html

【讨论】:

  • 请阅读我的更新。我无法将 @JsonIngore 添加到该类,因为它不是我的库,我无权访问它的源代码。
  • 您可以创建一个自定义克隆类并将其写入那里并序列化该类。效率不高,但有效
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-01
  • 2011-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多