gpt4 book ai didi

java - Jackson 解析类不起作用

转载 作者:行者123 更新时间:2023-12-02 11:16:19 27 4
gpt4 key购买 nike

我指的是这个tutorial学习 jackson 的基础知识,但严重陷入其中。

这是异常(exception):

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `hello.Car` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
at [Source: (String)"{"color":"Black","type":"BMW"}"; line: 1, column: 2]

这是:

@Builder
@Data
@AllArgsConstructor
public class Car implements Serializable {
private String color;
private String type;
}

这是解析逻辑:

@Service
public class HelloService {
public void testJackson() throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
String json1 = "{\"color\":\"Black\",\"type\":\"BMW\"}";
Car car1 = objectMapper.readValue(json1, Car.class);
}
}

仅供引用,我正在使用JacksonLombok:

    <dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.4</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.20</version>
<scope>provided</scope>
</dependency>

这到底是怎么回事。请分享一些想法。

更新 2018-05-10@Hemant Patel,谢谢。刚刚添加了 @NoArgsConstructor,就像魔术一样。它按预期工作。我会调查一下,看看到底发生了什么。

@Builder
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Car implements Serializable {
String color;
String type;
}

顺便说一句,谢谢@Thomas 和@Alex,我检查了这两篇帖子,但我真的不认为真正的原因在于与Lombok<的关系/em>。

最佳答案

经过一番查找,我从它的官方API中找到了这个documentation :

public ObjectMapper()

Default constructor, which will construct the default JsonFactory as necessary, use SerializerProvider as its SerializerProvider, and BeanSerializerFactory as its SerializerFactory. This means that it can serialize all standard JDK types, as well as regular Java Beans (based on method names and Jackson-specific annotations), but does not support JAXB annotations.

众所周知,什么是Java Bean(基于此post):

A JavaBean is just a standard

  1. All properties private (use getters/setters)
  2. A public no-argument constructor
  3. Implements Serializable.

关于java - Jackson 解析类不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50253841/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com