Gson Map Key对json

时间:2013-09-24 15:46:03

标签: android json serialization

我想解析JSON:

Map<Pair<String, Date>, Product>

由于JSON不能有一个对有键,它显然给了我这样的东西:

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

此时为了实现我的目标,我将不得不创建我的Pair<String, Date>对象序列化和反序列化方法。

这是我需要你帮助的地方,我不知道该怎么做。我是否必须创建MyPair类扩展Pair并实施JsonSerializer<Pair<String, Date>> ...?




修改
所以我试图使用TypeAdapter<T>,但没有运气......

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);
}
}

但是当我注册我的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()));


此:

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

给我NullPointerException ... 为什么呢?

1 个答案:

答案 0 :(得分:0)

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

好的,所以我错过了这个importante选项:

            .enableComplexMapKeySerialization()

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

希望它有所帮助!