Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Say I have a very simple java object that only has some getXXX and setXXX properties. This object is used only to handle values, basically a record or a type-safe (and performant) map. I often need to covert this object to key value pairs (either strings or type safe) or convert from key value pairs to this object.

Other than reflection or manually writing code to do this conversion, what is the best way to achieve this?

An example might be sending this object over jms, without using the ObjectMessage type (or converting an incoming message to the right kind of object).

like image 348
Shahbaz Avatar asked Apr 11 '09 07:04

Shahbaz


People also ask

How do you create a key value pair object in Java?

Pair<String, String> keyValue = new ImmutablePair("key", "value");

How do you convert an object in Java?

Convert Object to String in java using toString() method of Object class or String. valueOf(object) method. Since there are mainly two types of class in java, i.e. user-defined class and predefined class such as StringBuilder or StringBuffer of whose objects can be converted into the string.

How do you use key value pairs in Java?

Java HashMap class implements the Map interface which allows us to store key and value pair, where keys should be unique. If you try to insert the duplicate key, it will replace the element of the corresponding key. It is easy to perform operations using the key index like updation, deletion, etc.

Which method is used to retrieve key and value pairs?

To retrieve the set of keys from HashMap, use the keyset() method.


2 Answers

Lots of potential solutions, but let's add just one more. Use Jackson (JSON processing lib) to do "json-less" conversion, like:

ObjectMapper m = new ObjectMapper(); Map<String,Object> props = m.convertValue(myBean, Map.class); MyBean anotherBean = m.convertValue(props, MyBean.class); 

(this blog entry has some more examples)

You can basically convert any compatible types: compatible meaning that if you did convert from type to JSON, and from that JSON to result type, entries would match (if configured properly can also just ignore unrecognized ones).

Works well for cases one would expect, including Maps, Lists, arrays, primitives, bean-like POJOs.

like image 81
StaxMan Avatar answered Oct 11 '22 08:10

StaxMan


There is always apache commons beanutils but of course it uses reflection under the hood

like image 45
Maurice Perry Avatar answered Oct 11 '22 10:10

Maurice Perry