Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ObjectMapper Module for Id de-/serialization #2849

Merged
merged 2 commits into from
Oct 13, 2023

Conversation

marecabo
Copy link
Contributor

@marecabo marecabo commented Oct 12, 2023

This change adds a Module, that configures a Jackson ObjectMapper such that it can natively de-/serialize Id<T> classes, even when nested in Lists or Maps.

This is a prerequisite for storing link ids in the network for enabling turn restrictions in #2829.

Example

Map<Id<Link>, String> map = new LinkedHashMap<>();
map.put(Id.createLinkId("0"), "a");
map.put(Id.createLinkId("1"), "b");

// create & configure ObjectMapper
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(IdDeSerializationModule.getInstance());

// create & configure ObjectWriter
TypeFactory typeFactory = TypeFactory.defaultInstance();
MapType mapType = typeFactory.constructMapType(
		Map.class, 
		typeFactory.constructParametricType(Id.class, Link.class),
 		typeFactory.constructType(String.class));
ObjectWriter objectWriter = objectMapper.writerFor(mapType);

// serialize
String s = objectWriter.writeValueAsString(map); // {"0":"a","1":"b"}

// deserialize
Map<Id<Link>, String> deserializedMap = objectMapper.readValue(s, mapType);

Bonus Improvement

The @JsonId annotation from #2667 also got generalized to work for any Id<T> class.

record RecordWithIds(
	@JsonId Id<Person> personId,
	@JsonId Id<Link> linkId
) {};
class ClassWithIds {
	@JsonId
	public Id<Person> personId;
}

This code now is a blueprint for de-/serializing even parametrized classes. We should be able to write records with complex types that easily can be de-/serialized using Jackson.

Great thanks @mrieser for the support with the generalization!

@marecabo marecabo force-pushed the id-serialization branch 3 times, most recently from d5ee1ec to 27bd756 Compare October 12, 2023 13:43
@marecabo marecabo self-assigned this Oct 13, 2023
@marecabo marecabo requested a review from michalmac October 13, 2023 09:51
@marecabo marecabo merged commit 3cd3946 into matsim-org:master Oct 13, 2023
46 checks passed
@marecabo marecabo deleted the id-serialization branch October 13, 2023 10:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant