gpt4 book ai didi

java - 无法读取 JSON : Cannot construct instance of `java.util.LinkedHashMap`

转载 作者:行者123 更新时间:2023-12-02 10:37:57 26 4
gpt4 key购买 nike

如果我得到将得到不确定的行 JSON 数据。我应该如何设置我的类(class)?

这是我当前的类(class)

public class ChatMessage {

private Map<String, String> message = new HashMap<>();

@JsonAnyGetter
public Map<String, String> any(){
return this.message;
}

public Map<String, String> getMessage() {
return this.message;
}

@JsonAnySetter
public void setMessage(String key, String value) {
message.put(key, value);
}

@Override
public String toString() {
return "Message [message=" + message + "]";
}
}

这是我从 js 发送的 json

{"type":"message","user":"james","to":"","message":"Hi every"}

我现在遇到错误

org.springframework.messaging.converter.MessageConversionException: Could not 
read JSON: Cannot construct instance of `java.util.LinkedHashMap` (although
at least one Creator exists): no String-argument constructor/factory method
to deserialize from String value ('Welcome james join the room')
at [Source: (byte[])" .
{"type":"message","user":"james","to":"","message":"Welcome james join the
room"}"; line: 1, column: 52] (through reference chain:
chat.model.ChatMessage["message"]); nested exception is
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct
instance of `java.util.LinkedHashMap` (although at least one Creator exists):
no String-argument constructor/factory method to deserialize from String
value ('Welcome james join the room')
at [Source: (byte[])" .
{"type":"message","user":"james","to":"","message":"Welcome james join the
room"}"; line: 1, column: 52] (through reference chain:
chat.model.ChatMessage["message"])

因为我的 json 会像

{"type":"message",
"user":"james",
"to":"",
"message":"Welcome james join the room",
"xxx":"xxxxxxxxxxxxx"}

{"type":"message",
"user":"james",
"to":"",
"message":"Welcome james join the room",
"yyy":"xxxxxxxxxxxxx"}

我应该如何设置我的类(class)?谢谢

最佳答案

重命名 json 中的 message 字段或 POJO 中的 message 字段。根据您的 POJO 结构,jackson 正在尝试将 "message":"Hi every" 反序列化到 POJO 中的消息字段,并且无法从中创建映射(因为它只是一个字符串) )。

您的代码将使用以下 json:

{"type":"message","user":"james","to":"","json-message":"Hi every"}

或者

以下 POJO:

public class ChatMessage {

private Map<String, String> map = new HashMap<>();

@JsonAnyGetter
public Map<String, String> any(){
return this.map;
}

public Map<String, String> getMap() {
return this.map;
}

@JsonAnySetter
public void setMap(String key, String value) {
map.put(key, value);
}

@Override
public String toString() {
return "Map [map=" + map + "]";
}
}

关于java - 无法读取 JSON : Cannot construct instance of `java.util.LinkedHashMap` ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53144626/

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