gpt4 book ai didi

java - 无法使用 Jackson 将对象序列化为 Json

转载 作者:行者123 更新时间:2023-12-02 04:06:49 25 4
gpt4 key购买 nike

我正在尝试使用 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;
}

最佳答案

看起来您的一个类有 java.io.FileDescriptor 引用。

By default, Jackson will only work with with fields that are either public, or have a public getter methods – serializing an entity that has all fields private or package private will fail

如果您查看java.io.FileDescriptor的源代码,您可以 see有没有公​​共 getter 的私有(private)字段。

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

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

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

关于java - 无法使用 Jackson 将对象序列化为 Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34204364/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com