[英]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/ ) :我的用例包括一个类似的类,使用不可变( https://immutables.github.io/ ):
@Value.Immutable
@Gson.TypeAdapters
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 :我正在使用 gson 将其转换为 Json 字符串,然后使用以下命令再次获取对象:
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 :但是现在我不得不将 var1 更改为字符串列表,现在我得到了:
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 ?从 JSON 字符串获取对象的正确方法是什么?
Figured out what was wrong, hence answering the question.弄清楚出了什么问题,因此回答了这个问题。 Immutables generated class GsonAdaptersSampleClass, which implements TypeAdapterFactory.
不可变生成类 GsonAdaptersSampleClass,它实现了 TypeAdapterFactory。 Using this and with the help of this answer : https://stackoverflow.com/a/13624060/3192744
使用这个并在这个答案的帮助下: https : //stackoverflow.com/a/13624060/3192744
I could find the following correct way to deserialize JSON string:我可以找到以下反序列化 JSON 字符串的正确方法:
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapterFactory(new GsonAdaptersSampleClass());
Gson gson = gsonBuilder.create();
SampleClass obj1 = gson.fromJson("generated_json_string",ImmutableSampleClass.class);
You can try GSON library for converting JSON to your existing class object.您可以尝试使用 GSON 库将 JSON 转换为现有的类对象。
http://howtodoinjava.com/best-practices/google-gson-tutorial-convert-java-object-to-from-json/ http://howtodoinjava.com/best-practices/google-gson-tutorial-convert-java-object-to-from-json/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.