Lithicas Lithicas - 1 month ago 7
JSON Question

@RequestBody, sending in List<String> in POST request

I have a basic POJO with a field shown below:

@NotEmpty
@ElementCollection
@Column(name = "TAGS")
private List<String> tags;


I'm trying to send a JSON formatted POST request to the following controller:

@RequestMapping(value = "/post", method = RequestMethod.POST)
public void createPost(@RequestBody BlogPost blogPost) {
blogPostService.addPost(blogPost);
}


My JSON:

{
"stuff": "stuff",
"stuff": "stuff",
"tags": [{"Tag 1"}, {"Tag 2"}]
}


Basically my issue is that I have no idea how to convert that in to a List. I have tried searching for answers but I haven't found anything. Is this even possible?

The error I get is:


JSON parse error: Can not deserialize instance of java.lang.String out of START_OBJECT token;

Answer Source
"tags": [{"Tag 1"}, {"Tag 2"}]

correspond to an array of object, not an array of String that should be represented like :

"tags": ["Tag 1", "Tag 2"]

Either change the client side to send an array of String : "tags": ["Tag 1", "Tag 2"].

Otherwise, change the client side and the backend side to declare a List that is parameterized with a custom class that will contain the String value.

Json to send :

"tags": [{"value": "Tag 1"}, {"value": "Tag 2"}]

mapping in the back end :

private List<MyObject> tags;

Where MyObject could be declared :

public class MyObject{
   private String value;
   ... // getter - setter
}