Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON - deserialization of dynamic object using Gson

Tags:

java

json

gson

Let's imagine I have a Java class of the type:

public class MyClass
{
   public String par1;
   public Object par2;
}

Then I have this:

String json = "{"par1":"val1","par2":{"subpar1":"subval1"}}";

Gson gson = new GsonBuilder.create();
MyClass mClass = gson.fromJson(json, MyClass.class);

The par2 JSON is given to me from some other application and I don't ever know what are it's parameter names, since they are dynamic.

My question is, what Class type should par2 variable on MyClass be set to, so that the JSON String variable is correctly deserialized to my class object?

Thanks

like image 714
RedEagle Avatar asked Jan 12 '12 02:01

RedEagle


People also ask

How do I parse dynamic JSON fields with Gson?

According to GSON documentation you can do things like: Type mapType = new TypeToken<Map<Integer, Result> >() {}. getType(); // define generic type Map<Integer, Result> result= gson. fromJson(new InputStreamReader(source), mapType);

What is Gson Deserialization?

Deserialization in the context of Gson means converting a JSON string to an equivalent Java object. In order to do the deserialization, we need a Gson object and call the function fromJson() and pass two parameters i.e. JSON string and expected java type after parsing is finished.

Does Gson offer parse () function?

The GSON JsonParser class can parse a JSON string or stream into a tree structure of Java objects. GSON also has two other parsers. The Gson JSON parser which can parse JSON into Java objects, and the JsonReader which can parse a JSON string or stream into tokens (a pull parser).


1 Answers

Check out Serializing and Deserializing Generic Types from GSON User Guide:

public class MyClass<T>
{
   public String par1;
   public T par2;
}

To deserialize it:

Type fooType = new TypeToken<Myclass<Foo>>() {}.getType();
gson.fromJson(json, fooType);

Hope this help.

like image 119
yorkw Avatar answered Oct 11 '22 13:10

yorkw