5

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\"}"
}

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

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

Artanis
  • 561
  • 1
  • 7
  • 26

2 Answers2

6

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.

Jake Holzinger
  • 5,783
  • 2
  • 19
  • 33
3

First, make sure to have something like the following resource method:

@Path("/url")
public class Test {

    @POST
 @Consumes(MediaType.APPLICATION_JSON)
    public Response post(@RequestBody Foo foo) {
        ...
    }
}

Then, when you send the request through POSTMAN, select the type as POST, then select the "raw" option and then just send a JSON in the "body" with the values you want to put in your Map. Remember to select "application/json" . Jackson will transform the JSON into a Map for you.

{
   "myInt": 10,
   "myMap": {
         1: "A"
     }
}
programmer-man
  • 365
  • 3
  • 12