自定义GSON解串器

时间:2016-04-12 09:55:45

标签: android gson json-deserialization

我有以这种格式的多个API响应:

{
   status: "OK",
   error: null,
   data: [
   ]
}

“data”字段不同(单项和项目列表)...所以我写了一个自定义反序列化器:

public class CustomDeserializer<T> implements JsonDeserializer<ServerResponse<T>> {

private Type t;

public CustomDeserializer() {
}

public CustomDeserializer(Type t) {
    this.t = t;
}

@Override
public ServerResponse<T> deserialize(JsonElement je, Type type, JsonDeserializationContext jdc)
        throws JsonParseException {

    Gson gson = new Gson();

    ServerResponse<T> serverResponse = new ServerResponse<>();
    serverResponse.setError(gson.fromJson(je.getAsJsonObject(), Error.class));
    serverResponse.setStatus(gson.fromJson(je.getAsJsonObject(), ResponseStatus.class));

    if (je.getAsJsonObject().get("data").isJsonArray()) {
        JsonArray arr = je.getAsJsonObject().getAsJsonArray("data");
        T[] a = (T[]) new Object[arr.size()];

        for (int i = 0; i < arr.size(); i++) {
            a[i] = gson.fromJson(arr.get(i), t);
        }
        ((ServerResponse<List<T>>) serverResponse).setData(Arrays.asList(a));

        return serverResponse;
    } else {
        T data = gson.fromJson(je.getAsJsonObject().get("data"), t);
        serverResponse.setData(data);

        return serverResponse;
    }
}

}

Gson设置:

Gson gson = new GsonBuilder()
            .registerTypeAdapter(ServerResponse.class, new CustomDeserializer<Category>(Category.class))
            .registerTypeAdapter(ServerResponse.class, new CustomDeserializer<City>(City.class))
            .registerTypeAdapter(ServerResponse.class, new CustomDeserializer<Business>(Business.class))
            .registerTypeAdapter(ServerResponse.class, new CustomDeserializer<BusinessListItem>(BusinessListItem.class))
            .create();

但是当响应来了......反序列化器在错误的类中反序列化它......

您对我如何解决这个问题有什么建议吗?

1 个答案:

答案 0 :(得分:0)

这取决于您的数据结构。如果你有

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main()
{
    char again = 'y';
    while (again == 'y')


    int main()
        {

            srand(static_cast<unsigned int>(time (0)));
            int secret = rand() % 100 +1;
            int tries = 0;
            int guess;
            cout << "\tGuess the random number\n\n";

            do 
                {
                    cout << "Enter a guess: ";
                    cin >> guess;
                    ++ tries;
                    if (guess > secret)
                        {
                            cout << "Too High!\n\n:";
                        }
                    else if (guess < secret)
                        {
                            cout << "Too Low!\n\n";
                        }
                    else 
                        {
                            cout << "\nThat's It! You go it in " << tries << " guesses!\n";
                        }
} while (guess != secret);
}

cout << "\n\tWould you like to play again? (y/n): ";
char again;
cin >> again;


}

您可以使用此通用反序列化器:

<button class="button icon-left ion-radio-waves button-clear" ng-href="http://www.mywebsite.com" onclick="window.open(this.href, '_blank', 'location=no'); return false;"></button>

用例:

public static class ServerResponse<T>{
    private Error error;
    private ResponseStatus status;
    private List<T> data;
    // getters, setters , tostring
}

修改Deserializing JSON into a class with a generic argument using GSON or Jackson

之后发布更新
相关问题