Gson Map Key Pair to json

元气小坏坏 提交于 2019-12-23 05:18:05

问题


I want to parse to JSON this:

Map<Pair<String, Date>, Product>

Since JSON cannot have a Pair has key it obviously gives me something like this:

{"android.util.Pair@a24f8432":{"Name:"name","Brand":"brand"....}}

At this point to achieve my goal I'll have to create my Pair<String, Date> Object Serialize and Deserialize methods.

This is where I need your help, I have no idea how to do this. Do I have to create MyPair class extending Pair and implementing JsonSerializer<Pair<String, Date>> ...?




EDIT:
So I'm trying to use TypeAdapter<T> but with no luck...

public class MyTypeAdapter extends TypeAdapter<Pair<String, Date>> {

@Override
public Pair<String, Date> read(JsonReader jsonReader) throws IOException {
    if (jsonReader.peek() == JsonToken.NULL) {
        jsonReader.nextNull();
        return null;
    }

    String id = jsonReader.nextString();

    Date evaluated = null;

    try {
        evaluated = mySimpleDateFormat.parse(jsonReader.nextString());
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return new Pair<String, Date>(id,evaluated);
}

@Override
public void write(JsonWriter jsonWriter, Pair<String, Date> stringDatePair) throws IOException {
    if (stringDatePair == null) {
        jsonWriter.nullValue();
        return;
    }
    String output = stringDatePair.first + "," + stringDatePair.second;
    jsonWriter.value(output);
}
}

But when I register my TypeAdapter:

Type TYPE = new TypeToken<Pair<String, Date>>() {}.getType();


 GsonBuilder builder = new GsonBuilder();
    builder.registerTypeAdapter(TYPE, new MyTypeAdapter());
    Gson g = builder.create();
    String test = g.toJson(new Pair<String, Date>("123",new Date()));


This:

builder.registerTypeAdapter(TYPE, new MyTypeAdapter());

Gives me NullPointerException... Why?


回答1:


 Gson gson = new GsonBuilder()
                .registerTypeAdapter(TYPE, new MyTypeAdapter())
                .enableComplexMapKeySerialization()
                .create();

Ok so I was missing this importante option:

            .enableComplexMapKeySerialization()

http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/GsonBuilder.html#enableComplexMapKeySerialization%28%29

Hope it helps!



来源:https://stackoverflow.com/questions/18986269/gson-map-key-pair-to-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!