将JSON键值对映射到HashMap

3

我正在尝试将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 Spring 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;
}

尝试使用私有Map<String,List<String>> recipientStatus; - vikas kumar
尝试使用JsonObject替换map对象,看看是否可以正常工作。 - mehdi maick
@vikaskumar,那也不行。recipientStatus仍然为空。 - Chris
同样适用于你的解决方案,@mehdimaick。 - Chris
将recipientStatus替换为Object,并检查它是否为空,或将其替换为Map<String, Object>并再次测试。 - mehdi maick
你必须手动遍历来完成它。 - vikas kumar
3个回答

1
问题可能出在recipientStatus属性名称上。在Message对象和JSON中的名称不匹配。有多种方法可以解决这个问题:
  1. As @ddarellis suggested, rename property either in your Java class or in JSON so they will match.

  2. Mark Java property with @JsonProperty annotation

    public class Message {
        @JsonProperty("recipient_status")
        private Map<String, String> recipientStatus;
    }
    
  3. Set PropertyNamingStrategy on the deserializer to SNAKE_CASE either by modifying ObjectMapper

    new ObjectMapper().setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
    

    or with the JsonNaming annotation

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

0
你的问题在于recipient_status,你应该将其改为recipientStatus。你的JSON应该与POJO变量名匹配。不需要特别做什么来创建一个HashMap

-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

想象一下,你需要对生成的类进行一些更正。 希望这能有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接