Reputation: 57
Currently I have a Resource as follows
@PostMapping("/color")
public String addColorData(@RequestBody Object obj){
System.out.println(obj.toString());
return "200";
}
and when I POST the JSON bellow
{ "color" : "Green", "mixutres" : { "Yellow" : 0.5, "random2" : 0.5 } }
the print is as expected - {color=Green, mixutres={Yellow=0.5, random2=0.5}}
However,
When I make a class Color
public class Color {
private String color;
private Object mixtures;
public Object getMixtures() {
return mixtures;
}
public void setMixtures(Object mixtures) {
this.mixtures = mixtures;
}
and modify my Resource as bellow
@PostMapping("/color")
public String addColorData(@RequestBody Color colorObj){
System.out.println(colorObj.toString());
return "200";
}
mixtures ends up as 'null'
{color=Green, mixtures='null'}
Why does mixtures end up as 'null'?
Assuming that I don't know the exact structure of mixtures, is setting the Mixtures' type as Object the right approach? If not, could you guys give me some advice for best practices?
Thank you
--- Follow up --
Thanks to Gulliva found a typo in my JSON, when I tested after the edit
Spring returned the following
trace": "org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of
java.lang.String
out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance ofjava.lang.String
out of START_OBJECT token\n at [Source: (PushbackInputStream); line: 5, column: 18] (through reference chain:.... "message": "JSON parse error: Cannot deserialize instance of
java.lang.String
out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance ofjava.lang.String
out of START_OBJECT token\n at [Source: (PushbackInputStream); line: 5, column: 18] (through reference chain:
Upvotes: 1
Views: 394
Reputation: 555
If your structure is just key pair value then you can use Map<String, String> mixtures which is my preferred ds and your class would look like this :
public class Color {
private String color;
private Map<String, String> mixtures;
public Map<String,String> getMixtures() {
return mixtures;
}
public void setMixtures(Map<String,String> mixtures) {
this.mixtures = mixtures;
}
As by taking collection type of structure would be helpful in future as well for data accessing/modifying.
Upvotes: 1
Reputation: 488
If your example at top is correct, then you have a Typo in the key "mixtures".
One suggestions here. Consider to use ResponseBody to as your ResponseEntity. Since ResponseBody is a generic class you can use it with the type you like and set a HTTP StatusCode like
ResponseEntity.ok("hello world);
Upvotes: 0