gpt4 book ai didi

java - "JSON 解析错误 : Cannot construct instance of (although at least one Creator exists): cannot deserialize from Object value - SpringBoot

转载 作者:行者123 更新时间:2023-12-05 09:03:46 44 4
gpt4 key购买 nike

我正在使用 SpringBoot 和 Mongo 数据库,我正在尝试将嵌入式文档保存到数据库中。

我有这个模型:

配置文件.java

@Data
@Document
public class Profile {

public final City city;
public final String imageId;

public Profile(City city,
String imageId) {
this.city = city;
this.imageId = imageId;
}

@Override
public String toString() {
return "Profile{" +
", city=" + city +
", imageId='" + imageId + '\'' +
'}';
}

private static boolean atLeast(int numChars, String s) {
if (s == null) {
return false;
}
var str = s.strip();
return str.length() >= numChars;
}


public static ProfileBuilder builder() {
return new ProfileBuilder();
}

public static final class ProfileBuilder {
public City city;
public String imageId;

private ProfileBuilder() {
}


public ProfileBuilder withCity(City city) {
this.city = city;
return this;
}

public ProfileBuilder withImageId(String imageId) {
this.imageId = imageId;
return this;
}

public Profile build(){
return new Profile(city, imageId);
}
}
}

City.java

public class City {

public final String name;

public City(String name) {
this.name = name;
}

@Override
public String toString() {
return "City{" +
", name='" + name + '\'' +
'}';
}
}

ProfileController.java

 @RequestMapping( method = RequestMethod.POST)
public Profile addUser(@RequestBody Profile profile) {
return profileService.addProfile(profile);
}

我和 postman 一起发送这个 JSON

{
"city":{
"name":"Atena"
},
"imageId" : "Doe",
}
}

但我收到以下错误:

"JSON parse error: Cannot construct instance of `domain.City` (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator);"

最佳答案

至少有两种解决方案。

  1. @JsonCreator 添加到构造函数并将 @JsonProperty 添加到其参数(以指示 Jackson 如何以正确的顺序将 JSON 项替换到构造函数中)
class Profile {
...
@JsonCreator
public Profile(@JsonProperty("city") City city,
@JsonProperty("imageId") String imageId) {
this.city = city;
this.imageId = imageId;
}
...
}

(+ 与 City 类相同)

  1. Unfinal 类属性并提供默认的无参数构造函数(以及现有的全参数构造函数)。
class Profile {

public City city;
public String imageId;

public Profile() {
}

public Profile(City city, String imageId) {
this.city = city;
this.imageId = imageId;
}
}

(+ 与 City 类相同)

测试

class Test {
public static void main(String[] args) throws JsonProcessingException {
String json = "{\"city\":{\"name\":\"Atena\"},\"imageId\":\"Doe\"}";
Profile p = new ObjectMapper().readValue(json, Profile.class);
System.out.println(p);
}
}

输出:

Profile{, city=City{, name='Atena'}, imageId='Doe'}

关于java - "JSON 解析错误 : Cannot construct instance of (although at least one Creator exists): cannot deserialize from Object value - SpringBoot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69538090/

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