JSON parse error: Can not construct instance of io.starter.topic.Topic

后端 未结 2 1712
南笙
南笙 2020-12-29 23:44

Im learning Spring Boot and I made a demo but when I POST a request to add a Object it didn\'t work!

The error message is:

{
    \"timestamp\": 15168         


        
相关标签:
2条回答
  • 2020-12-30 00:30

    You need to annotate the constructor with @JsonCreator:

    Marker annotation that can be used to define constructors and factory methods as one to use for instantiating new instances of the associated class.

    NOTE: when annotating creator methods (constructors, factory methods), method must either be:

    • Single-argument constructor/factory method without JsonProperty annotation for the argument: if so, this is so-called "delegate creator", in which case Jackson first binds JSON into type of the argument, and then calls creator. This is often used in conjunction with JsonValue (used for serialization).
    • Constructor/factory method where every argument is annotated with either JsonProperty or JacksonInject, to indicate name of property to bind to

    Also note that all JsonProperty annotations must specify actual name (NOT empty String for "default") unless you use one of extension modules that can detect parameter name; this because default JDK versions before 8 have not been able to store and/or retrieve parameter names from bytecode. But with JDK 8 (or using helper libraries such as Paranamer, or other JVM languages like Scala or Kotlin), specifying name is optional.

    Like this:

    @JsonCreator
    public Topic(@JsonProperty("id") String id, @JsonProperty("name") String name,
                 @JsonProperty("author") String author, @JsonProperty("desc") String desc) {
        this.id = id;
        this.name = name;
        this.author = author;
        this.desc = desc;
    }
    
    0 讨论(0)
  • 2020-12-30 00:45

    For deserialisation purposes Topic must have a zero-arg constructor.

    For example:

    public class Topic {
        private String id;
        private String name;
        private String author;
        private String desc;
    
        // for deserialisation
        public Topic() {}    
    
        public Topic(String id, String name, String author, String desc) {    
            this.id = id;
            this.name = name;
            this.author = author;
            this.desc = desc;
        }
    
        // getters and setters
    
    }     
    

    This is the default behaviour of the Jackson library.

    0 讨论(0)
提交回复
热议问题