【问题标题】:Could not read JSON: Cannot construct instance of `java.util.LinkedHashMap`无法读取 JSON:无法构造 `java.util.LinkedHashMap` 的实例
【发布时间】: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


【解决方案1】:

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

您的代码将使用以下 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 + "]";
}
}

【讨论】:

  • 如果我们尝试将 objectname 从 message 更改为 json-message,jackson-object mapper 将如何识别并转换为 object?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-23
  • 2019-01-21
  • 1970-01-01
  • 1970-01-01
  • 2021-10-06
  • 2012-09-26
  • 2021-07-17
相关资源
最近更新 更多