JSON - deserializing a dynamic object using Gson

Suppose I have a Java class like:

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); 

par2 JSON is provided to me from another application, and I never know what these parameter names are, since they are dynamic.

My question is: what type of class should the par2 variable in MyClass have in order for the JSON String variable to be properly deserialized for my class object?

thanks

+7
source share
4 answers

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

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

For deserialization:

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

I hope for this help.

+7
source

See an answer from Kevin Dolan on this SO question: How to convert JSON to HashMap using Gson?

Please note that this is not an accepted answer and you may have to modify it a bit. But this is pretty amazing.

Alternatively, protect the security type of your top-level object and simply use hash cards and arrays. Less modification of Dolan code this way.

0
source

if your object has a dynamic name inside, let's say this:

 { "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()

0
source

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

it should be:

 Gson gson=new Gson() 

I think (if you are parsing a json document).

-4
source

Source: https://habr.com/ru/post/1390564/


All Articles