Jackson ObjectMapper无法反序列化POJO,抛出一个异常:没有为type[…]找到合适的构造函数:无法从JSON对象实例化

时间:2022-07-05 18:04:23

I have tried to test the following code with no success:

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

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

This problem is different from this one: Deserializing JSON with Jackson - Why JsonMappingException "No suitable constructor"?

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

and this one: JsonMappingException: No suitable constructor found for type [simple type, class ]: can not instantiate from JSON object

而这个:JsonMappingException:类型[简单类型,类]:无法从JSON对象实例化

and this one: JsonMappingException: No suitable constructor found for type [simple type, class ]: can not instantiate from JSON object

而这个:JsonMappingException:类型[简单类型,类]:无法从JSON对象实例化

as I have manually override the default constructor, and its not a subclass.

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

How do I fix this problem?

我如何解决这个问题?

2 个解决方案

#1


58  

Make it static. Jackson can not deserialize to inner classes

使其静态的。杰克逊不能对内部类进行反序列化。

#2


0  

The problem is probably that Jackson can't properly reach your ND2Customer class to invoke its constructor because it is private, as your class otherwise looks just fine. Try making it public and seeing if that works.

问题可能是,Jackson不能正确地到达您的ND2Customer类来调用它的构造函数,因为它是私有的,因为您的类看起来很好。试着将它公之于众,看看是否有效。

#1


58  

Make it static. Jackson can not deserialize to inner classes

使其静态的。杰克逊不能对内部类进行反序列化。

#2


0  

The problem is probably that Jackson can't properly reach your ND2Customer class to invoke its constructor because it is private, as your class otherwise looks just fine. Try making it public and seeing if that works.

问题可能是,Jackson不能正确地到达您的ND2Customer类来调用它的构造函数,因为它是私有的,因为您的类看起来很好。试着将它公之于众,看看是否有效。