Reputation: 53
I've been using Spring boot for a while now so I can say that I am pretty comfortable with using it.
However there is one problem that I can never solve. When I want my Spring boot server to consume a JSON object coming from the front end I usually use @RequestBody like this: If the JSON object looks like this:
{"name":"Jason"}
I would create a POJO like this:
public class User{
private String name;
public void setName(String name){
this.name=name;
}
public String getName(){
return this.name
}
}
And then in my main controller i would simply use @RequestBody like this:
@RequestMapping(value="createUser", method = RequestMethod.POST)
public void createUser(@RequestBody User user){
//code here
}
And this would work because the key "name" in the JSON object matches the attribute "name" of the Java User object.
However, in my current project there I have to consume a JSON objects with keys like {" # Name ":"Jason"}
In this case I can not create a POJO object with an attribute called # Name because obviously an object's attribute cannot start with # and cannot have spaces.
When faced with problems like this I usually do
@RequestBody HashMap<String, String> map
and then
User newUser = new User();
newUser.setName(map.get(" # Name"));
However when you have a JSON object with 40+ keys this can become troublesome.
Is there an easier way to parse JSON objects with keys that would appear invalid in Java like this?
Thanks a lot!
Upvotes: 2
Views: 1949
Reputation: 13114
Try annotating your name
member with @JsonProperty
.
@JsonProperty(" # name")
private String name;
This will allow the deserialiser to match the key in your JSON payload with your POJO member.
Upvotes: 4