Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing map using @JsonProperty

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));
    }
}
like image 598
user2512231 Avatar asked Dec 19 '25 20:12

user2512231


1 Answers

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:

  • that the annotations are placed on the methods
  • that the objects are immutable (if possible)
  • and that a proper @JsonCreator-method is added (the constructor work for your class but in order to create a more complex object structure @JsonCreator will help you).
like image 71
wassgren Avatar answered Dec 22 '25 10:12

wassgren



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!