我正在使用Gson,并希望将以下JSON替代项反序列化到同一个类Values
中。在后一种情况下,我希望只收到List
个元素。有没有办法在Gson中完成此操作而无需编写自定义反序列化器?
//Array:
{
"Value": [205.4, 13.5]
}
//Single value:
{
"Value": 205.4
}
将两者反序列化为:
public static class Values {
private List<Double> Value;
}
答案 0 :(得分:1)
除非使用自定义TypeAdapter
,否则无法在Gson中执行此操作。
public class AwesomeType extends ArrayList<Double> {
...
}
public class AwesomeTypeAdapter extends TypeAdapter<AwesomeType> {
@Override
public void write(JsonWriter out, AwesomeType value) throws IOException {
...
}
@Override
public AwesomeType read(JsonReader in) throws IOException {
AwesomeType result = new AwesomeType();
if (in.peek() == JsonToken.BEGIN_ARRAY) {
in.beginArray();
while (in.peek() != JsonToken.END_ARRAY)
result.add(in.nextDouble());
in.endArray();
} else {
result.add(in.nextDouble());
}
return result;
}
}
将此类型适配器注册到您的Gson,并在模型中使用此类而不是List<Double>
。
答案 1 :(得分:0)
@BornToCode提到解决方案是编写自定义get_include_path()
并将其注册到TypeAdapter
:
GsonBuilder
注册:
public class ListTypeAdapter extends TypeAdapter<List<Double>> {
@Override
public void write(final JsonWriter writer, final List<Double> doubles) throws IOException {
writer.beginArray();
for (final double value : doubles) {
writer.value(value);
}
writer.endArray();
}
@Override
public List<Double> read(final JsonReader reader) throws IOException {
final List<Double> doubles = new ArrayList<>();
if (reader.peek() == JsonToken.BEGIN_ARRAY) {
reader.beginArray();
while (reader.hasNext()) {
doubles.add(reader.nextDouble());
}
reader.endArray();
} else {
doubles.add(reader.nextDouble());
}
return doubles;
}
}