【发布时间】:2018-11-04 19:34:12
【问题描述】:
如果我得到一个不确定的行 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"}
我应该如何设置我的班级? 谢谢
【问题讨论】:
-
这是如何工作的?转换为对象后您是否尝试过检查?
标签: java json spring-boot jackson