2

我从服务器收到以下响应:

“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的结果包始终为空,为什么?

4

0 回答 0