-1

When using gson to a class, one of the classes variables can either be a String or a List. Is it possible to catch and fix this without making a whole new class where one class has String and the other List?

Here is an example of the class:

public class JsonClass
{
    private List<Integer> range;

    public List<Integer> getRange() { return range; }
}

This only works when the range is a List with Integers, but it can also just be a String. The gson message is: "Expected STRING but was BEGIN_ARRAY".

Aucun
  • 11
  • 3
  • Java doesn't allow two methods with the same name (and same parameter types)... therefore you have to keep track of both instances either by separating them into classes, or just keep different fields `String strRange` and `List range` as well as your getter methods: `public List getRange()` and `public String getStrRange()` – gtgaxiola Sep 22 '14 at 13:58

2 Answers2

0

I don't think that u can do that. String and List are totally different things. As Java is strongly typed, u should create a new class to be able to deal it with 2 ways

Lelouchzqy
  • 249
  • 1
  • 10
0

You have two problems.

First, how will your code use this JsonClass if it doesn't know the type of range. You can declare it as Object, but you'll have to check the instance type and cast it every time. Alternatively, you can have two variables, one for each type. But then, what do you do with the other? Do you leave it null? Do you put a default value, empty list, empty string? These are things you should consider first.

Second, Gson, by default, looks at the declared type of a field in order to deserialize JSON. If you declare it as Object, it will use some known defaults. What you can do is create and register a TypeAdapter which will contain logic for deserializing both a JSON array and a JSON string depending on what it finds.

I don't recommend either of the approaches above. I suggest you try to fix the JSON you are receiving to send a single type or map it to different types based on some external information, ie. not based on the JSON itself.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724