简体   繁体   English

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

[英]Unable to serialize Object to Json using Jackson

I'm trying to serialize an object in Java using Jackson, but when I'm trying to serialize it, it gives me this error: 我正在尝试使用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. 我尝试了这篇文章,但没有帮助。

Here is the class I'm trying to serialize: 这是我要序列化的类:

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;
}

I also tried to create getters/setters for each field but still nothing. 我还尝试为每个领域创建吸气剂/吸气剂,但仍然一无所获。

Here is my serialization method: 这是我的序列化方法:

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;
    } 

Looks like your one of your classes has java.io.FileDescriptor reference. 看起来您的一个类具有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 默认情况下,Jackson将仅使用公共字段或具有公共getter方法的字段-序列化具有所有私有字段或私有软件包的实体将失败

If you look at the source code of java.io.FileDescriptor you can see there are private fields without public getters. 如果查看java.io.FileDescriptor的源代码,则可以看到存在没有公共获取器的私有字段。

You should configure your objectMapper visibility to allow access to private fields also. 您应该配置objectMapper可见性以允许也访问私有字段。

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

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

I was facing problems to send objects to Thymeleaf template with ResponseEntity it was giving me exception "StackOverFlowError" while serializing and your note " @JsonIgnore // to avoid recursive calls" solved my problem. 我遇到了使用ResponseEntity将对象发送到Thymeleaf模板的问题,它在序列化时给了我异常“ StackOverFlowError”,并且您的注释“ @JsonIgnore //避免递归调用”解决了我的问题。 Thanks 谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM