Jackson ObjectMapper 无法反序列化 POJO,引发异常:找不到适合类型的构造函数 [...] :无法从 JSON 对象实例化

2022-09-01 21:52:38

我尝试测试以下代码但没有成功:

class TestClass
{
  private class ND2Customer
  {
    public String name;
    public String description;
    public String email;
    public Boolean multiuser;

    public String dnszone;
    public String uri;
    public String type;

    public ND2Customer()
    {

    }
  }

  @Test
  public void TestJackson() throws JsonParseException, JsonMappingException, IOException
  {
    String json="{\"description\": \"test1u\", \"dnszone\": \"test1.public.sevenltest.example.com.\", \"uri\": \"http://199.127.129.69/customer/test1\", \"multiuser\": true, \"type\": \"2.0.3-3146\", \"email\": \"test1@com.com\", \"name\": \"test1\"}";
    ObjectMapper mapper = new ObjectMapper();

    ND2Customer casted=mapper.readValue(json, ND2Customer.class);

    String castedback=mapper.defaultPrettyPrintingWriter().writeValueAsString(casted);
    System.out.println(castedback);
  } 
}

这个问题与这个问题不同:用Jackson反序列化JSON - 为什么JsonMappingException“没有合适的构造函数”?

和这个: JsonMappingException:没有为类型[简单类型,类]找到合适的构造函数:无法从JSON对象实例化

和这个: JsonMappingException:没有为类型[简单类型,类]找到合适的构造函数:无法从JSON对象实例化

因为我手动覆盖了默认构造函数,它不是子类。

如何解决此问题?


答案 1

使其静态。Jackson 不能反序列化为内部类


答案 2

问题可能是 Jackson 无法正确访问您的类来调用其构造函数,因为它是 ,因为您的类在其他方面看起来很好。尝试制作它,看看是否有效。ND2Customerprivatepublic