GSON如何反序列化键值对JSON对象?

时间:2015-12-17 15:37:58

标签: android gson parcelable android-bundle

我从服务器得到以下回复:

“data”: {
    “key1”: 11
    “key2”: 89
    “key3”: {
        “key7”: 1
        “key8”: -1
        “key11”: 1
    },
    “key5”: “test”
}

我做了一个可以模仿的模型:

class Model implements Parcelable {
    private int key1;
    private int key2;
    private Bundle key3;
    private int key5;

    [...]

    protected Model(Parcel in) {
        key1 = in.readInt();
        [...]
        key3 = in.readBundle();
    }

    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(key1);
        [...]
        dest.writeBundle(key3);
    }
}

我正在以这种方式初始化GSON:

private static final Gson GSON = new GsonBuilder()
        .registerTypeAdapterFactory(new ItemTypeAdapterFactory())
        .create();

我的ItemTypeAdapterFactory:

class ItemTypeAdapterFactory implements TypeAdapterFactory {

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

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

        return new TypeAdapter<T>() {

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

            public T read(JsonReader in) throws IOException {

                JsonElement jsonElement = elementAdapter.read(in);
                if (jsonElement.isJsonObject()) {
                    JsonObject jsonObject = jsonElement.getAsJsonObject();

                    // JSON key "data"
                    if (jsonObject.has("data")) {

                        JsonElement jsonData = jsonObject.get("data");

                        // JSON primitive
                        if (jsonData.isJsonPrimitive()) {
                            jsonElement = jsonData.getAsJsonPrimitive();
                        }

                        // JSON object
                        else if (jsonData.isJsonObject()) {
                            jsonElement = jsonData;
                        }

                        // JSON object array
                        else if (jsonData.isJsonArray()) {
                            jsonElement = jsonData.getAsJsonArray();
                        }
                    }
                }

                return delegate.fromJsonTree(jsonElement);
            }
        }.nullSafe();
    }
}

key3的结果包始终为空,为什么?

0 个答案:

没有答案