8

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

Perception
  • 79,279
  • 19
  • 185
  • 195
RedEagle
  • 4,418
  • 9
  • 41
  • 64
  • Are you tied to Gson? Your use case could be handled much better with a free-form JSON processor like json-simple (http://code.google.com/p/json-simple). – Perception Jan 12 '12 at 03:09

4 Answers4

9

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.

yorkw
  • 40,926
  • 10
  • 117
  • 130
  • 6
    I don't think this helps the OP. He does not know what type the object is going to be before he performs the deserialization. – Perception Jan 12 '12 at 03:32
0

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.

Community
  • 1
  • 1
ccoakley
  • 3,235
  • 15
  • 12
-1

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

Johnny Cage
  • 5,526
  • 2
  • 11
  • 7
-6

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

should be:

Gson gson=new Gson()

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

lanyimo
  • 367
  • 1
  • 3
  • 13