I try to serialize an object that contains a Map using the @JsonProperty annotation, but when I tested it I saw that only the keys of the map are serialized. I looked it up but found no solution, what am I doing wrong?
public class People {
private final Map<Long,String> idToNameMap;
public People(@JsonProperty("idToNameMap") final Map<Long,String> idToNameMap) {
this.idToNameMap = idToNameMap;
}
}
public class PeopleTest {
private static final long ID_1 = 111l;
private static final long ID_2 = 222l;
private static final String NAME_1 = "name1";
private static final String NAME_2 = "name2";
private final ObjectMapper mapper = new ObjectMapper();
@Test
public void testFromAndToJSON() throws Exception {
Map<Long,String> idToNameMap = Maps.newHashMap();
idToNameMap.put(ID_1,NAME_1);
idToNameMap.put(ID_2,NAME_2);
mapper.writeValueAsString(new People(idToNameMap));
}
}
You have not provided any serialization information for the People-class, only deserialization info.
The following should work out for you:
public class People {
private final Map<Long, String> idToNameMap;
// The constructor works for deserialization and has nothing to do with serialization
public People(@JsonProperty("idToNameMap") final Map<Long, String> idToNameMap) {
this.idToNameMap = idToNameMap;
}
// Getters are typically automatically serialized
public Map<Long, String> getIdToNameMap() {
return idToNameMap;
}
}
There are multiple ways to provide the serialization info. Another approach would be to use the @JsonProperty annotation for a method - e.g like this:
@JsonProperty("idToNameMap")
public Map<Long, String> getMapping() {
return idToNameMap;
}
Or, another approach is to put the annotation on the actual field. This is not something I would recommend because it is somewhat magic.
public class People {
@JsonProperty("idToNameMap")
private final Map<Long, String> idToNameMap;
public People(@JsonProperty("idToNameMap") final Map<Long, String> idToNameMap) {
this.idToNameMap = idToNameMap;
}
}
I personally prefer:
@JsonCreator-method is added (the constructor work for your class but in order to create a more complex object structure @JsonCreator will help you).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