Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping a JSON key value pair to HashMap

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;
}
like image 836
Chris Avatar asked Dec 30 '25 00:12

Chris


1 Answers

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:

  1. As @ddarellis suggested, rename property either in your Java class or in JSON so they will match.

  2. Mark Java property with @JsonProperty annotation

    public class Message {
        @JsonProperty("recipient_status")
        private Map<String, String> recipientStatus;
    }
    
  3. 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.

like image 140
Nikolay K Avatar answered Dec 31 '25 15:12

Nikolay K



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!