Home > Enterprise >  Java: How to map json keys which include dots?
Java: How to map json keys which include dots?

Time:04-06

I have a json in which some of its keys include dots. for example:

{
    "key.1" : 10,
    "key.2" : 20,
    "key.3" : 30
}

I was planning to use Jackson to map it into a MyClass model object using something like:

ObjectMapper mapper = new ObjectMapper();
MyClass obj = mapper.readValue(json, MyClass.class

Of course I cannot create class members with dots in their names.

So, is there a way to overcome this situation?

Jackson is preferred but not mandatory.

CodePudding user response:

Just use the annotation @JsonProperty on top of the field declaration, with a name that is different than the field's name:

@JsonProperty("key.1")
private final int key1;
@JsonProperty("key.2")
private final int key2;
@JsonProperty("key.3")
private final int key3;

As a general note, Jackson will map the Json key to the field name only if you don't specify anything else (so it will go by reflection). However, with Jackson is possible to modify the names of the fields (and not only) using their annotations.

As a side note, you'll also need to annotate the constructor parameters to deserialize the object from Json to Java object:

@JsonCreator
public MyClass(
    @JsonProperty(value = "key.1", required = true) int key1,
    @JsonProperty(value = "key.2", required = true) int key2,
    @JsonProperty(value = "key.3", required = true) int key3) {
    this.key1 = key1;
    this.key2 = key2;
    this.key3 = key3;
}

... then you will be able to do what you wanted:

MyClass obj = mapper.readValue(json, MyClass.class);
  • Related