【问题标题】:Jackson ObjectMapper Exception: Invalid type definition for type "Person"Jackson ObjectMapper 异常:“Person”类型的类型定义无效
【发布时间】:2021-04-29 12:19:38
【问题描述】:

我得到这个异常:

com.fasterxml.jackson.databind.exc.InvalidDefinitionException:类型'main.Person'的类型定义无效:无法为[简单类型,类main.Person]构造BeanSerializer:(java.lang.reflect.InaccessibleObjectException)无法使公共 java.lang.String main.Person.getFirstname() 可访问:模块 JsonTest 不会“将 main”“导出”到模块 com.fasterxml.jackson.databind

我是杰克逊的新手,我不明白出了什么问题。 我在网上找不到任何东西,所以也许你可以帮助我。

我的代码如下:

public class Person {

    private String firstname;
    private String lastname;
    private int id;

    public Person(String firstname, String lastname, int id) {
        this.firstname = firstname;
        this.lastname = lastname;
        this.id=id;
    }
    public String getFirstname() {
            return this.firstname;
    }

    public void setFirstname(String firstname) {
           this.firstname = firstname;
    }
     public String getLastname() {
            return this.lastname;
     }

    public void setLastname(String firstname) {
           this.lastname = firstname;
    }
    public int getId() {
        return this.id;
    }
    public void setId(int id) {
        this.id = id;
    }
}
import java.io.File;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Test {
    
    public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        File file = new File("Desktop/test.json");
        
        Person per = new Person("peter","lol",2);
        objectMapper.writeValue(file, per);
    }
}

没有什么特别的但仍然无法正常工作:( 我将 Jackson .jar 库导入到我的 Eclipse java 项目中,也许这是您需要的信息。

问候

【问题讨论】:

  • 看起来你正在使用java的模块系统。所以你必须将你的包导出到 person 类所在的位置。否则 Jackson 无法访问它。
  • 谢谢这是问题!

标签: java json jackson objectmapper


【解决方案1】:

解决方案是我需要在模块中导出我的包

module JacksonTest {
    requires com.fasterxml.jackson.databind;
    exports myPackage; // <--- Solution
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-02
    • 2012-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多