NimChimpsky
NimChimpsky

Reputation: 47290

Spring basic pojo from JSON using Jackson within Spring

@JsonCreator
public Foo( @JsonProperty("title") String title,
            @JsonProperty("strTags") Collection<String> strTags) {
        this.title = title;
        this.strTags = strTags;
}

and the method sig looks like this:

@RequestMapping(value = "/Preview", method = RequestMethod.POST)
public ModelAndView preview(@RequestBody final Foo foo) {..}

And the test is:

String json = "\"foo\":{\"title\":\"test\",\"strTags\":[\"Tag1\",\"tag2\"]}";
MvcResult mvcResult =  this.mockMvc.perform(
  post("/Preview/").contentType(MediaType.APPLICATION_JSON).content(json))
    .andExpect(status().isOk())
    .andExpect(model().attributeExists("foo"))
    .andExpect(view().name("foo/preview"))
    .andDo(print())
    .andReturn();
}

However, I get the error:

no suitable creator method found to deserialize from JSON String

Upvotes: 1

Views: 760

Answers (1)

miku
miku

Reputation: 188024

The properties title and strTags should be top-level, like this:

String json = "{\"title\":\"test\",\"strTags\":[\"Tag1\",\"tag2\"]}";

Upvotes: 3

Related Questions