fweigl
fweigl

Reputation: 22028

Generalizing field names with Gson

I have a JSON objext that looks like this:

       {
               "isDefault": false,
               "someIndex":
               [
                   0
               ],
               "label": "Hello",
               "valueKindName": "someId",
               "value": 3,
               "conditions":
               {
                   "salesType":
                   [
                       1,
                       2
                   ],
                     "productType":
                   [
                       1,
                       5
                   ]
               }
           }

Now my Conditions class looks like this:

public class Conditions {

private List<Integer> salesType = new ArrayList<Integer>();
private List<Integer> productType = new ArrayList<Integer>();

}

This works. What I want to do is to generalize my class so that I could any new type to the conditions like:

   "exampleType":
                   [
                       6,
                       9
                   ]

without having to add

private List<Integer> exampleType = new ArrayList<Integer>();

to my Conditions.class.

I have thought of the following:

public class Conditions {

    private ArrayList<Condition> conditions = new ArrayList<Condition>();
}

and

public class Condition {

    private String key;
    private ArrayList<Integer> values;
}

but Gson of course doesn't know how to convert the JSON to that type of data structure.

Any help would be highly apprectiated :)

Upvotes: 0

Views: 147

Answers (1)

Greg Kopff
Greg Kopff

Reputation: 16595

You can register your own converter. It would look a little like this:

public class ConditionConverter implements JsonSerializer<Condition>, JsonDeserializer<Condition>
{
  @Override
  public JsonElement serialize(Condition src, Type typeOfSrc, JsonSerializationContext context)
  {
    final JsonObject cond = new JsonObject()
    cond.add(src.key, context.serialise(src.values);

    return cond;
  }

  public Condition deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
      throws JsonParseException
  {
    // pick apart and make a condition again
  }
}

You then register the type adapter with your GsonBuilder:

builder.registerTypeAdapter(Condition.class, new ConditionConverter());

To pick apart your object, you'll need to use JsonObject.entrySet(), as you don't know the key name beforehand. Your job would be slightly easier if you adopted JSON like this:

{
  key: "exampleType",
  values: [ 42, 43 ]
}

Upvotes: 1

Related Questions