[Data format conversion error can't create non-static inner class instance. Reason ]

Table of contents

 reason: 

Test trivia:


 

 reason: 

This error is usually because when using a JSON parsing library such as Gson or Jackson to convert a JSON string into a Java object, the Java object contains a non-static inner class (that is, a nested class), and the parsing library cannot create a non-static inner class. caused by the instance.

The non-static inner class depends on the existence of the instance of the outer class, so when creating an instance of the non-static inner class, you need to create an instance of the outer class first. When the JSON parsing library creates a Java object, it only calls the default constructor of the Java class to create the object, but does not create an instance of an external class, so it cannot create an instance of a non-static internal class.

There are two ways to solve this problem:

  1. Change the non-static inner class to a static inner class or a separate outer class so you can create objects directly.

  2. Customize a JsonDeserializer to handle deserialization of non-static inner classes. Specifically, an instance of the outer class needs to be manually created in JsonDeserializer and passed to the constructor of the non-static inner class to create the object. Here is a sample code:

public class MyDeserializer implements JsonDeserializer<MyClass> {
    @Override
    public MyClass deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        JsonObject jsonObject = json.getAsJsonObject();
        String name = jsonObject.get("name").getAsString();
        int age = jsonObject.get("age").getAsInt();
        JsonObject innerObject = jsonObject.get("inner").getAsJsonObject();
        InnerClass inner = context.deserialize(innerObject, InnerClass.class);
        MyClass myClass = new MyClass(name, age, inner);
        myClass.setOuter(new OuterClass());
        return myClass;
    }
}

Test trivia:

I created the main method in a test class, and then created an inner class A

Then in the main method, the data Object data is converted into the specified A object format mapping, and the internal class of A does not add Static (I didn’t pay attention to when the static was dropped by me, carelessly)

JSON.toJSONString(data), A.class);

Guess you like

Origin blog.csdn.net/sqL520lT/article/details/131540354