简体   繁体   English

JSON - 使用Gson反序列化动态对象

[英]JSON - deserialization of dynamic object using Gson

Let's imagine I have a Java class of the type: 让我们假设我有一个类型的Java类:

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. par2 JSON是从其他应用程序给我的,我不知道它的参数名称是什么,因为它们是动态的。

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? 我的问题是,要将MyClass上的par2变量设置为什么类类型,以便将JSON String变量正确反序列化为我的类对象?

Thanks 谢谢

Check out Serializing and Deserializing Generic Types from GSON User Guide: 查看GSON用户指南中的序列化和反序列化通用类型

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. 希望这有帮助。

if you object has dynamic name inside lets say this one: 如果你的对象里面有动态名称,那就说这个:

{
    "Includes": {
        "Products": {
            "blablabla": {
                "CategoryId": "this is category id",
                "Description": "this is description",
                ...
}

you can serialize it with: 您可以使用以下命令序列化它:

MyFunnyObject data = new Gson().fromJson(jsonString, MyFunnyObject.class);

@Getter
@Setter
class MyFunnyObject {
    Includes Includes;
    class Includes {
        Map<String, Products> Products;
        class Products {
            String CategoryId;
            String Description;
        }
    }
}

later you can access it: 以后你可以访问它:

data.getIncludes().get("blablabla").getCategoryId()

See the answer from Kevin Dolan on this SO question: How can I convert JSON to a HashMap using Gson? 请参阅Kevin Dolan关于这个问题的答案: 如何使用Gson将JSON转换为HashMap?

Note, it isn't the accepted answer and you'll probably have to modify it a bit. 请注意,这不是可接受的答案,您可能需要对其进行一些修改。 But it's pretty awesome. 但它非常棒。

Alternatively, ditch the type safety of your top-level object and just use hashmaps and arrays all the way down. 或者,抛弃顶级对象的类型安全性,并一直使用哈希映射和数组。 Less modification to Dolan's code that way. 这种方式对Dolan代码的修改较少。

this code: Gson gson = new GsonBuilder.create(); 这段代码: Gson gson = new GsonBuilder.create();

should be: 应该:

Gson gson=new Gson()

i think(if you are parsing a json doc). 我想(如果你正在解析一个json doc)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM