JSON-使用Gson反序列化动态对象 [英] JSON - deserialization of dynamic object using Gson

查看:167
本文介绍了JSON-使用Gson反序列化动态对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们想象一下,我有一个类型的Java类:

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

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

然后我有这个:

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

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

par2 JSON是通过其他应用程序提供给我的,我不知道它的参数名称是什么,因为它们是动态的.

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.

我的问题是,应将MyClass上的par2变量设置为哪种Class类型,以便将JSON String变量正确反序列化为我的类对象?

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?

谢谢

推荐答案

查看

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

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

要反序列化它:

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

希望获得帮助.

这篇关于JSON-使用Gson反序列化动态对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆