【问题标题】:Unable to serialize Object to Json using Jackson无法使用 Jackson 将对象序列化为 Json
【发布时间】:2015-12-10 14:26:56
【问题描述】:

我正在尝试使用 Jackson 序列化 Java 中的对象,但是当我尝试序列化它时,它给了我这个错误:

No serializer found for class java.io.FileDescriptor and no properties discovered to create BeanSerializer

I tried this post, but it didn't help.

这是我要序列化的类:

public class Repository {
    public String name;
    @JsonIgnore   // to avoid recursive calls
    public ArrayList<UserRole> contributors = new ArrayList<UserRole>();
    public User self;
    public ArrayList<FileInfo> files;
    public RepositoryType repositoryType;
    public String path;
}

我还尝试为每个字段创建 getter/setter,但仍然没有。

这是我的序列化方法:

public static String convertObjectToJson(Object object) throws IOException {
        ObjectWriter objectWriter = new ObjectMapper().writer().withDefaultPrettyPrinter();
        String json = objectWriter.writeValueAsString(object); //error on this line
        return json;
    } 

【问题讨论】:

  • 什么是FileInfo?你希望Jackson怎么连载它?
  • 杰克逊为什么不能序列化呢?当我将对象传递给序列化程序时,文件字段为空。

标签: java json serialization jackson


【解决方案1】:

看起来你的一门课程有 java.io.FileDescriptor 参考。

默认情况下,Jackson 只会使用公共字段或具有公共 getter 方法的字段 - 序列化具有所有字段私有或包私有的实体将失败

如果你看java.io.FileDescriptor的源代码你可以see 有没有公​​共 getter 的私有字段。

您应该配置您的 objectMapper 可见性以允许访问私有字段。

// For jackson 2.*
objectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);

// For jackson lower than 2
objectMapper.setVisibility(JsonMethod.FIELD, Visibility.ANY);

【讨论】:

  • 谢谢,我没有使用 fileDescriptro,但是将 ObectWriter 更改为 ObjectMapper 并设置可见性解决了问题。
【解决方案2】:

我在使用 ResponseEntity 将对象发送到 Thymeleaf 模板时遇到了问题,它在序列化时给了我异常“StackOverFlowError”,而您的注释“@JsonIgnore // 以避免递归调用”解决了我的问题。谢谢

【讨论】:

猜你喜欢
  • 2019-08-21
  • 1970-01-01
  • 2011-12-23
  • 2013-01-08
  • 2023-03-13
  • 2017-12-10
  • 2014-02-12
  • 2012-04-06
  • 1970-01-01
相关资源
最近更新 更多