如何调用默认的反序列化与GSON [英] How to invoke default deserialize with gson

查看:315
本文介绍了如何调用默认的反序列化与GSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到一个JSON,有场领域。
如果场中有数据,再有就是有很多(约20)等领域,同时也是对象的对象。我可以反序列化他们没有任何问题。
但是,如果字段没有数据,这是一个空数组(我知道这是疯了,但是这是从服务器的响应,我不能改变它)。 事情是这样的:

I get a json that has "field" field.
If the "field" has data, then there is an OBJECT that has many (about 20) other fields that are also objects. I can deserialize them without any problems.
But if "field" has no data, it is an empty ARRAY (I know it's crazy, but that's the response from server and I can't change it). Something like this:

当空的:

"extras":[

]

有一些数据:

"extras": {
    "22":{ "name":"some name" },
    "59":{ "name":"some other name" },
    and so on...
}

所以,当如果没有数据(空数组),我显然得到的异常

So, when there if no data (empty array), I obviously get the exception

Caused by: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException:
Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 4319

我试图用自定义JavaDeserializer:

I tried to use custom JavaDeserializer:

public class ExtrasAdapter implements JsonDeserializer<Extras> {

@Override
public Extras deserialize(JsonElement json, Type typeOf, 
              JsonDeserializationContext context) throws JsonParseException {
    try {
        JsonObject jsonObject = json.getAsJsonObject();
                    // deserialize normally 

                    // the following does not work, as it makes recursive calls 
                    // to the same function 
        //return context.deserialize(jsonObject, 
                    //                       new TypeToken<Object>(){}.getType());
    } catch (IllegalStateException e) {
        return null;
    }
}

}

我读了JSON以下方式

I read the json the following way

Gson gsonDecoder = new GsonBuilder().registerTypeAdapter(Extras.class, new ExtrasAdapter();
// httpResponse contains json with extras filed. 
Reader reader = new InputStreamReader(httpResponse.getEntity().getContent());
Extras response = gsonDecoder.fromJson(reader, Extras.class);

我不想手动反序列化的所有20场(我知道这是一个选项),我只是想打电话给context.defaultDeserialize(),或者类似的东西。
再次声明:我没有正常的反序列化JSON,创建自定义对象,注册自定义TypeAdapters,定制JavaDeserializers任何问题。这一切工作了。我只需要用于处理数据的一些解决方案,即既可以是数组和对象。
感谢您的帮助。

I don't want to deserialize all 20 fields manually (I know this is an option), I just want to call context.defaultDeserialize(), or something like that.
Once again: I don't have any problems deserializing normal json, creating custom objects, registering custom TypeAdapters, custom JavaDeserializers. It all works already. I need only some solution for handling a data, that can be both ARRAY and OBJECT.
Thanks for any help.

======================


在乔伊的回答可以完美运行。该权利的事情,我一直在寻找。 我会在这里发布我的code。

======================


The Joey's answer works perfect. That right the thing I was looking for. I'll post my code here.

public class SafeTypeAdapterFactory implements TypeAdapterFactory {

public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {

    final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);

    return new TypeAdapter<T>() {

        public void write(JsonWriter out, T value) throws IOException {
            try {
                delegate.write(out, value);
            } catch (IOException e) {
                delegate.write(out, null);
            }
        }

        public T read(JsonReader in) throws IOException {
            try {
                return delegate.read(in);
            } catch (IOException e) {
                Log.w("Adapter Factory", "IOException. Value skipped");
                in.skipValue();
                return null;
            } catch (IllegalStateException e) {
                Log.w("Adapter Factory", "IllegalStateException. Value skipped");
                in.skipValue();
                return null;
            } catch (JsonSyntaxException e) {
                Log.w("Adapter Factory", "JsonSyntaxException. Value skipped");
                in.skipValue();
                return null;
            }

        }
    };
}

}

推荐答案

尝试使用GSON> = 2.2.1,并寻找<一href="http://google-gson.google$c$c.com/svn/trunk/gson/docs/javadocs/com/google/gson/TypeAdapterFactory.html">TypeAdapterFactory类。

Try using GSON >= 2.2.1 and look for the TypeAdapterFactory class.

这将给你检查的对象,你反序列化之前和应用自定义code,同时避免递归的能力。

This will give you the ability to inspect the Object before you deserialize it and apply custom code while avoiding recursions.

下面是的<一个例子href="http://google-gson.google$c$c.com/svn/trunk/gson/docs/javadocs/com/google/gson/Gson.html#getDelegateAdapter%28com.google.gson.TypeAdapterFactory,%20com.google.gson.reflect.TypeToken%29">getDelegateAdapter你可以使用。

这篇关于如何调用默认的反序列化与GSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆