sameer sameer - 4 months ago 8
JSON Question

Defining class for GSON with heterogeneous list of String and Integers

I want to use GSON for converting object to json string.
json string is

"type": "both", "value": ["numbercodes", [1, 2, 3]]


As you can see "value" is list of String followed by Array of Integers so how can I represent heterogenuos list of String and numbers

Following code won't work:

class X
{
String type;
List<List<String>> value;
}


OR even following code wont work:

class Value
{
String x1;
List<Integer> x2;
}
class X
{
String type;
Value value;
}


AND:

Gson gson = new Gson();
X x = new X();
String jsonString = gson.toString(x);


But value of jsonString wont be as per expectation.

"type": "both", "value": ["numbercodes", [1, 2, 3]]

SO HOW should I define my class "X" such that I get above json string.

Answer

The best solution would be refactoring the data model. Always write code being clear to other developers, so they can understand what the model represents. It should be like the example below:

{
    "type": "both",
    "someKey": "numbercodes",
    "arrayOfIntegers": [1, 2, 3]
}

And then your entity class would be just:

class Entity {
    String type;
    String someKey;
    List<Integer> arrayOfIntegers;
}

The current model doesn't really says what "numbercodes" and the array of integers are. There are plenty of ways you can change it, I've just proposed one.

EDIT:

If you really want to stay with the current model, it should be just:

class Entity {
    String type;
    List<Object> value = new ArrayList<>();
    ...
    public void addValue(Object valueToAdd){
        value.add(valueToAdd);
    }
}

...

Entity entity = new Entity();
entity.setType("both");
entity.addValue("numbercodes");
entity.addValue(Arrays.asList(1,2,3));