GuilhE
GuilhE

Reputation: 11891

Gson Map Key Pair to json

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?

Upvotes: 0

Views: 814

Answers (1)

GuilhE
GuilhE

Reputation: 11891

 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!

Upvotes: 1

Related Questions