在邮递员邮寄请求中发送地图

2022-01-22 00:00:00 dictionary json post postman java

当我希望它使用@RequestBody 注释直接映射到我的Java pojo 时,我找不到关于如何在我的json 帖子中格式化地图的好答案.我假设 json 看起来像:

I can't find a good answer as to how to format a map in my json post when I want it to map directly to my Java pojo with the @RequestBody annotation. I'm assuming the json would look something like:

{
    "myInt":"10",
    "myMap":"{1:"A"}"
}

我的 pojo 将有一个 myInt 字段和一个 myMap 字段.myMap 字段的类型为 Map

My pojo would have a myInt field and a myMap field. The myMap field is of type Map<Integer,String>

地图的 json 是什么样子才能让它工作?

What does the json for the map look like to get this to work?

推荐答案

根据你的 JSON 结构 myMap 是一个 String.但是,即使您从 myMap 的值中删除引号,您也会发现 {1:"A"} 不是有效的 JSON,有效的 JSON 语法要求所有属性键是字符串.一个有效的 JSON 结构看起来像 {"1":"A"}.反序列化器应该能够将密钥强制转换为 Integer,所以 Map 就可以了.

According to your JSON structure myMap is a String. However, even if you remove the quotes from the value of myMap you will find that {1:"A"} is not valid JSON, valid JSON syntax requires that all property keys are strings. A valid JSON structure would look like {"1":"A"}. The deserializer should be able to coerce the key into an Integer, so Map<Integer, String> is fine.

相关文章