简体   繁体   中英

JSON - deserialization of dynamic object using 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

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.

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?

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.

this code: Gson gson = new GsonBuilder.create();

should be:

Gson gson=new Gson()

i think(if you are parsing a json doc).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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