0

I want to provide a POST servlet that takes the following JSON content:

{
  "name": John
  "age": 25,
  "some": "more",
  "params: "should",
  "get": "mapped"
}

Two of those properties should be explicit mapped to defined parameters. All other parameters should go into a Map<String, String>.

Question: how can I let Spring map them directly into the map of the bean?

@RestController
public void MyServlet {
   @PostMapping
   public void post(@RequestBody PostBean bean) {

   }
}

public class PostBean {
   private String name;
   private String age;

   //all other json properties should go here
   private Map<String, String> map;
}
membersound
  • 81,582
  • 193
  • 585
  • 1,120
  • Did you consider this: https://stackoverflow.com/questions/39916520/mapping-a-dynamic-json-object-field-in-jackson ? – Andremoniy Sep 13 '17 at 13:04
  • That would require an extra "payload" parameter in the json. But I cannot change the JSON that get's posted. – membersound Sep 13 '17 at 13:05
  • 2
    That post contains useful link in commentaries: http://www.cowtowncoder.com/blog/archives/2011/07/entry_458.html – Andremoniy Sep 13 '17 at 13:07

1 Answers1

0
public class PostBean {
    private Map<String, String> map;

    @JsonAnyGetter
    public Map<String, String> getMap() {
        return map;
    }

    @JsonAnySetter
    public void setMap(String name, String value) {
        if (this.map == null) map = new HashMap<>();
        this.map.put(name, value);
    }
}
membersound
  • 81,582
  • 193
  • 585
  • 1,120
  • 1
    When posting answers, it's important that you post more than code, make sure to explain your answers – bren Sep 13 '17 at 14:22
  • Well, the question is how to add all parameters to the `Map`. The answer is simple and the code provides a complete example. The clear difference between the question and answer is the `@JsonAnyGetter/Setter`. So no need to write further explanation. – membersound Sep 13 '17 at 15:03