RJN_WLY RJN_WLY - 1 year ago 168
Java Question

How to get object from json string, for Java class containing a list, generated using Immutables?

my use case included a similar class, using immutables (https://immutables.github.io/) :

public abstract class SampleClass {
public abstract String var1();
public abstract String var2();
public abstract Date date1();

I was converting it to Json string,using gson, and then getting the object again using :

SampleClass obj1 = new Gson().fromJson("generated_json_string",ImmutableSampleClass.class);

But now I had to change var1 to List of String, and now I am getting :

java.lang.RuntimeException: Failed to invoke com.google.common.collect.ImmutableList() with no args

What is the correct way to get the object from JSON string ?

Answer Source

Figured out what was wrong, hence answering the question. Immutables generated class GsonAdaptersSampleClass, which implements TypeAdapterFactory. Using this and with the help of this answer : http://stackoverflow.com/a/13624060/3192744

I could find the following correct way to deserialize JSON string:

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapterFactory(new GsonAdaptersSampleClass());
Gson gson = gsonBuilder.create();
SampleClass obj1 = gson.fromJson("generated_json_string",ImmutableSampleClass.class);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download