将JSON键值对映射到HashMap

时间:2017-12-24 14:08:03

标签: java json spring-boot

我正在尝试将json中的键值对(recipient_status)映射到Map<String, String>对象。除了这一个,所有字段都被正确解析。还有另一种解析键值对的方法吗?

我发送以下JSON字符串:

{
  "id": "layer:///messages/940de862-3c96-11e4-baad-164230d1df67",
  "parts": [
    {
      "id": "layer:///messages/940de862-3c96-11e4-baad-164230d1df67/parts/0",
      "mime_type": "text/plain",
      "body": "This is the message."
    }
  ],
  "sent_at": "2014-09-09T04:44:47+00:00",
  "recipient_status": {
    "layer:///identities/777": "sent",
    "layer:///identities/999": "read",
    "layer:///identities/111": "delivered",
    "layer:///identities/1234": "read"
  },
  "position": 120709792
}

到我的Java Sprint Boot后端

@RequestMapping(method = RequestMethod.POST, value = "/")
public String conversationCreated(@RequestBody Message message) {
}

并尝试将其解析为以下对象:

@Data
public class Message {
    private String id;

    private List<Part> parts;

    private LocalDateTime sentAt;

    private Map<String, String> recipientStatus;

    private Long position;
}

3 个答案:

答案 0 :(得分:0)

您的问题出现在recipient_status,您应该将其更改为recipientStatus。您的JSON应与POJO变量名称匹配。无需做一些特殊的事情来制作HashMap

答案 1 :(得分:0)

问题可能在于recipientStatus属性名称。 Message对象中的名称与JSON之间不匹配。有多种方法可以解决这个问题:

  1. 正如@ddarell所建议的那样,在Java类或JSON中重命名属性,以便它们匹配。

  2. 使用@JsonProperty注释标记Java属性

    public class Message {
        @JsonProperty("recipient_status")
        private Map<String, String> recipientStatus;
    }
    
  3. 通过修改PropertyNamingStrategy

    ,将解串器上的SNAKE_CASE设置为ObjectMapper
    new ObjectMapper().setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
    

    或使用JsonNaming注释

    @JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
    public class Message {
        private Map<String, String> recipientStatus;
    }
    
  4. 我认为在你的情况下,第三种选择更可取。您已在此命名策略中拥有两个属性,并且在不考虑您需要添加另一个JsonProperty的情况下添加新字段会更容易。此外,可以针对整个应用程序全局设置此策略。

答案 2 :(得分:-1)

如果您不确定该问题,请使用http://json2csharp.com/网站检查您生成的json类,如下所示: enter image description here

看什么? json完全支持我的生成器,它无法转换json。

所以在这里,您需要更改json片段中的recipient_status部分。

建议:

将recipient_status更改为以下内容:

 "recipient_status": {
     "sent":"layer:///identities/777",
     "read":["layer:///identities/999","layer:///identities/1234"],
     "delivered":"layer:///identities/111",
 }

json2csharp.com的生成器运行良好: enter image description here

认为您需要对生成的类进行一些修正。 希望有所帮助。

相关问题