1

I am using Google's GSON package http://code.google.com/p/google-gson/

I am converting JSON to Java.

I have this fragment of code where I do the conversion.

Gson gson = new Gson();
Type collectionType = new TypeToken<Collection<QueryProperty>>() {}.getType();
Collection<QueryProperty> queryProperties = gson.fromJson(query, collectionType);

My QueryProperty class has these fields (with getters/setters):

int id;
String uri;
String name;
Set<QueryValue> values;
String selected;

The QueryValue class had these fields (with getters/setters) perviously:

int id;
String uri;
String name;

I now want to be able to have different types of QueryValue.

I want to add a NumericQueryValue class (subclass of QueryValue), so I can pass in a set of bounds with which to query the db.

double lower;
double upper;

And want to make a new ResourceQueryValue (subclass of QueryValue) which looks the same as QueryValue used to:

int id;
String uri;
String name;

Is there anyway I can make this work. That is have a generic QueryValue class, but have the correct subclass returned depending on the parameters that the JSON supplies.

If I have not been clear please do let me know.

Ankur
  • 50,282
  • 110
  • 242
  • 312

2 Answers2

2

Gson does not currently have a simple mechanism for polymorphic deserialization, other than implementing custom deserialization processing. The next release looks like it will provide a built-in solution.

Previous StackOverflow.com Questions And Answers (Some With Examples) On This Topic:

Community
  • 1
  • 1
Programmer Bruce
  • 64,977
  • 7
  • 99
  • 97
  • Thanks for all the pointers, using Jackson might be the simplest solution (reading this http://programmerbruce.blogspot.com/2011/05/deserialize-json-with-jackson-into.html) – Ankur Jun 21 '11 at 13:44
1

Sounds like you want to create a custom deserializer if you need to check the values, or an instance creator if you only need to create an instance based on type.

Kaj
  • 10,862
  • 2
  • 33
  • 27
  • Thanks Kaj, I missed the instance creator explanation for some reason. I think that might be the way to go. – Ankur Jun 21 '11 at 13:29
  • A custom InstanceCreator is probably not the route to take. InstanceCreators are for creating objects with default values -- not for custom deserialization processing. Note that by default they don't even have reference to the deserialization context -- because they're not intended to be used to replace custom deserializers. InstanceCreators are useful when you absolutely have to use a particular constructor, and it's for some reason unacceptable for Gson to use the no-argument constructor (which it otherwise effectively uses, even if it's not provided by the coder or the compiler). – Programmer Bruce Jun 21 '11 at 13:32