I am trying to map a key value pair in json, recipient_status below, to a Map<String, String> object. All fields get parsed correctly, except this one. Is there another way I should parse a key value pair?
I am sending the following JSON string:
{
"id": "layer:///messages/940de862-3c96-11e4-baad-164230d1df67",
"parts": [
{
"id": "layer:///messages/940de862-3c96-11e4-baad-164230d1df67/parts/0",
"mime_type": "text/plain",
"body": "This is the message."
}
],
"sent_at": "2014-09-09T04:44:47+00:00",
"recipient_status": {
"layer:///identities/777": "sent",
"layer:///identities/999": "read",
"layer:///identities/111": "delivered",
"layer:///identities/1234": "read"
},
"position": 120709792
}
To my Java Sprint Boot backend
@RequestMapping(method = RequestMethod.POST, value = "/")
public String conversationCreated(@RequestBody Message message) {
}
And try to parse it into the following object:
@Data
public class Message {
private String id;
private List<Part> parts;
private LocalDateTime sentAt;
private Map<String, String> recipientStatus;
private Long position;
}
The problem is probably with recipientStatus property name. There is no match between the name in the Message object and JSON. There are multiple ways to solve this problem:
As @ddarellis suggested, rename property either in your Java class or in JSON so they will match.
Mark Java property with @JsonProperty annotation
public class Message {
@JsonProperty("recipient_status")
private Map<String, String> recipientStatus;
}
Set PropertyNamingStrategy on the deserializer to SNAKE_CASE either by modifying ObjectMapper
new ObjectMapper().setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
or with the JsonNaming annotation
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
public class Message {
private Map<String, String> recipientStatus;
}
I think that in your case the third option is preferable. You already have two properties in this naming strategy, and it would be easier to add new fields without thinking that you need to add another JsonProperty. Also, this strategy can be set globally for the whole application.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With