如果我将获得不确定的行JSON数据。我应该如何设置我的课程?
这是我目前的课程
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"}
我应该如何设置课程? 谢谢
答案 0 :(得分:1)
重命名json中的message
字段或POJO中的message
字段。
根据您的POJO结构,杰克逊试图将"message":"Hi every"
反序列化为POJO中的消息字段,并且无法从中创建Map(因为它只是一个字符串)。
您的代码将与以下json一起使用:
{"type":"message","user":"james","to":"","json-message":"Hi every"}
OR
遵循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 + "]";
}
}