如何使用 Gson 将响应序列化为对象?



我直接向VK api提出请求token

像这样:https://api.vk.com/method/groups.get?fields=photo_50&access_token=MY_TOKEN&filter=admin%2C%20editor%2C%20moder&extended=1这是关于 api 的规范 但是我无法使用Gson将响应序列化为对象,因为响应数组有int值:

{
"response": [
2,
{
"gid": 59295,
"name": "Создание",
"screen_name": "book",
"is_closed": 0,
"type": "group",
"photo_50": "https://pp.userapi.com/qwvD6SPkYzo.jpg"
},
{
"gid": 57150,
"name": "Массаж",
"screen_name": "club10450",
"is_closed": 2,
"type": "group",
"photo_50": "https://pp.userapi.com/ZKnmRkS1izs.jpg"
}
]
}

如何使用Gson将其序列化为对象?

尽管您已经通过 GET URL 参数更改 API 版本解决了该问题,但这里有一种处理您将来可能遇到的"非标准"JSON 的方法。我假设你有正确的映射,但数组长度(大概)被作为第一个数组元素。Gson 本身无法处理这样的特殊情况(至少如果它需要{...}对象),可能会给你这样的东西:

预期BEGIN_OBJECT,但在第 3 行第 10 列路径 $.response[0] 处编号

假设您有类似于以下两个的映射:

final class ElementsResponse {
@SerializedName("response")
final List<Element> response = null;
}
final class Element {
@SerializedName("gid")
final int gid = Integer.valueOf(0);
@SerializedName("name")
final String name = null;
@SerializedName("screen_name")
final String screenName = null;
@SerializedName("is_closed")
final int isClosed = Integer.valueOf(0);
@SerializedName("type")
final String type = "";
@SerializedName("photo_50")
final URL photo50 = null;
}

您可以使用特殊类型的适配器工厂轻松创建类型适配器,以便处理给定的 JSON:

final class LengthArrayTypeAdapterFactory
implements TypeAdapterFactory {
// The instance holds no state and can be created as a singleton    
private static final TypeAdapterFactory lengthArrayTypeAdapterFactory = new LengthArrayTypeAdapterFactory();
private LengthArrayTypeAdapterFactory() {
}
// However, the factory method does not let a caller to create an instance itself, and _may_ create it itself if necessary (encapsulation)
static TypeAdapterFactory getLengthArrayTypeAdapterFactory() {
return lengthArrayTypeAdapterFactory;
}
@Override
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> typeToken) {
// Are we dealing with a java.util.List instance?
if ( List.class.isAssignableFrom(typeToken.getRawType()) ) {
// Resolve the list element type if possible
final Type elementType = getElementType(typeToken.getType());
// And request Gson for the element type adapter
final TypeAdapter<?> elementTypeAdapter = gson.getAdapter(TypeToken.get(elementType));
// Some Java boilerplate regarding generics in order not letting the @SuppressWarnings annotation cover too much
@SuppressWarnings("unchecked")
final TypeAdapter<T> castTypeAdapter = (TypeAdapter<T>) new LengthArrayTypeAdapter<>(elementTypeAdapter);
return castTypeAdapter;
}
// Or let Gson pick the next downstream type adapter itself
return null;
}
private static Type getElementType(final Type listType) {
// The given type is not parameterized?
if ( !(listType instanceof ParameterizedType) ) {
// Probably the (de)serialized list is raw being not parameterized
return Object.class;
}
final ParameterizedType parameterizedType = (ParameterizedType) listType;
// Or just take the first type parameter (java.util.List has one type parameter only)
return parameterizedType.getActualTypeArguments()[0];
}
private static final class LengthArrayTypeAdapter<E>
extends TypeAdapter<List<E>> {
// This type adapter is designed to read and write a single element only
// We'll take care of all elements array ourselves
private final TypeAdapter<E> elementTypeAdapter;
private LengthArrayTypeAdapter(final TypeAdapter<E> elementTypeAdapter) {
this.elementTypeAdapter = elementTypeAdapter;
}
@Override
public List<E> read(final JsonReader in)
throws IOException {
// Gson type adapters are supposed to be null-friendly
if ( in.peek() == NULL ) {
return null;
}
// Consume the array begin token `[`
in.beginArray();
// The next value is most likely the array length?
final int arrayLength = in.nextInt();
final List<E> list = new ArrayList<>();
// Read until the array has more elements
while ( in.hasNext() ) {
// And let the element type adapter read the array element so push the value to the list
list.add(elementTypeAdapter.read(in));
}
// Consume the array end token `]`
in.endArray();
assert arrayLength == list.size();
return list;
}
@Override
@SuppressWarnings("resource")
public void write(final JsonWriter out, final List<E> list)
throws IOException {
if ( list == null ) {
// Must be null-friendly always
out.nullValue();
} else {
// Writing the `[` token
out.beginArray();
// Writing the list size/length
out.value(list.size());
for ( final E element : list ) {
// And just write each array element
elementTypeAdapter.write(out, element);
}
// Finalizing the writing with `]`
out.endArray();
}
}
}
}

因此,您所要做的就是将类型适配器工厂添加到Gson配置中,创建特殊的阵列感知Gson

final Gson gson = new GsonBuilder()
.registerTypeAdapterFactory(getLengthArrayTypeAdapterFactory())
.create();
final ElementsResponse elementsResponse = gson.fromJson(JSON, ElementsResponse.class);
elementsResponse.response.forEach(e -> System.out.println(e.name));
System.out.println(gson.toJson(elementsResponse));

输出:

Создание Массаж{"response":[2,{"gid":59295,"name":"Создание","screen_name":"book","is_closed":0,"type":"group","photo_50":"https://pp.userapi.com/qwvD6SPkYzo.jpg"},{"gid":57150,"name":">

Массаж
","screen_name":"club10450","is_closed":2,"type":"group","photo_50":"https://pp.userapi.com/ZKnmRkS1izs.jpg"}]}

请注意,此类型适配器工厂始终假定第一个数组元素是一个数字,如有必要,您可能需要分析elementType(例如,如果它是java.lang.Number或其子类)。

已解决,在 url 中添加了参数v=5.61版本号

{
"response": {
"count": 190,
"items": [{
"id": 28261334,
"name": "TJ",
"screen_name": "tj",
"is_closed": 0,
"type": "page",
"is_admin": 0,
"is_member": 1,
"photo_50": "https://pp.vk.me/...f2c/06crfCSL1KY.jpg"
}]
}
}

最新更新