Java Jackson JSON, how to handle custom keys?

92 Views Asked by At

I am having difficulties with handling custom property names, or property names with a value that I am not sure how to handle, in my POJO class.

For example, when I retrieve this JSON body:

{
  "status":"success",
  "data": {
    "reels":{
      "highlight:17934390836227915":{
        "id":"highlight:17934390836227915"

What I want to do, is use the ObjectMapper to map "highlight:17934390836227915" as a member of reels, however I am not sure how to handle this as a property name, to the example below:

    public static class Reels{
        @JsonProperty("highlight")
        private Highlight highlight;

I can map properties, such as status to the variable status fine:

public static class Data{
        @JsonProperty("status")
        private String status;

So I can either process the JSON response body as a string, replace "highlight:179381431" with "highlight", but I do not believe this is an appropriate way, and that I am missing something.

I have tried to use @JsonProperty("highlight"+id), but the bean only accepts constant values which is something I'm not going to be doing, as there will be many different IDs.

1

There are 1 best solutions below

0
knittl On

Simplest option is probably to declare reels as a Map with String keys:

@Data
public class Reel {
  @JsonProperty("id")
  private String id;
}

@Data
public class Data {
 @JsonProperty("status")
 private String status;
 @JsonProperty("reels")
 private Map<String, Reel> reels;
}

You should then be able to access the reel from your sample input with:

data.getReels().get("highlight:17934390836227915")

Using a loop, you can match keys based on a pattern:

for (final Map.Entry<String, Reel> entry : data.getReels().getEntrySet()) { 
  if (entry.getKey().startsWith("highlight:")) {
    final Reel reel = entry.getValue();
    // ...
  }
}