mottosan
mottosan

Reputation: 486

Flattening an object graph to a map

I'm trying to flatten an object graph completely to a map.

Complex objects should also be flattened to the top level using "namespaces". So if the object A contains an int i, a string pid and another object B that contains a string id, the resulting Map would look like {i=1, pid="test", B.id="test1"}.

I also want to be able to reconstruct the original object from a given map.

I've searched around for libraries that do this. But I'm not quite getting what I'm looking for. I see stuff that maintains the hierarchy but nothing that completely flattens the structure.

I do see something in Spring Integration that looks like what I want to do: http://static.springsource.org/spring-integration/api/org/springframework/integration/transformer/ObjectToMapTransformer.html#ObjectToMapTransformer%28%29

But I can't get it to work.

Any help would be appreciated.

Thanks.

Upvotes: 4

Views: 3700

Answers (3)

Federico Bellini
Federico Bellini

Reputation: 504

The json-flattener library solves exactly your problem

Upvotes: 0

mottosan
mottosan

Reputation: 486

The Apache BeanUtils library has a describe() method that does something similar to what I was looking for.

Another possible solution would be via the Jackson JSON library, since JSON objects are essentially key-value pairs.

Related discussions: How to convert a Java object (bean) to key-value pairs (and vice versa)?

Upvotes: 1

Amir Afghani
Amir Afghani

Reputation: 38531

Have you considered using Protobufs?

Upvotes: 0

Related Questions