Convert LinkedHashMap <String, String> to an object in Java

I will start right with my question, and later I will give more background information.

Simple : I hava a LinkedHashMap<String, String> , and it represents a specific object. What is the best way to convert it to this object?

I know that you can use generics to go through all the elements and set the fields, but what are whit inested objects?

Background . I have a JAX-RS service that uses JSON objects. My service processes various objects and is an interface. Therefore, I do not know what objects come from outside and which program uses my service.

At runtime, I get information through @Inject on my interface. The JAX-RS service stores data from the client in an untyped object and runs automatically (this is LinkedHashMap<String, String> ).

In my interface, I want to provide a method such as setObject , and the parameter must be an object of this type. I can handle all of this, but not the part where I convert the LinkedHashMap<String, String> Object to this particular object.

Structure Example : Targets May Like

 public class Document { private String title; private String id; private int version; } 

LinkedHashMap looks like this:

 {title=some title, id=1, version=1} 
+4
source share
2 answers

You can create two classes

 @XmlAccessorType(XmlAccessType.FIELD) public class Document { @XmlElement private String title; @XmlElement private String id; @XmlElement private int version; } @XmlAccessorType(XmlAccessType.FIELD) public class MapJson { @XmlElement private LinkedHashMap<String, String> documents; } 

and cobvert Object to JSON usingg
Jackson

 new org.codehaus.jackson.map.ObjectMapper().writeValueAsString(instanceofMapJson); 

Google json

 new com.google.gson.Gson().toJson(instanceofMapJson); 

PS. Using google json you can remove xml annotations from your classes

+3
source

Reflection is the only way to set the properties of a common unknown object.
You can find everything you need in the documents.

+1
source

All Articles