问题
I want to use GSON to decode an array of maps in which the keys are not Strings. I know that the JSON type does not allow for objects to be used as keys, so I was hoping it is possible to have GSON work recursively to decode Strings.
Java
public class Reader {
static class Key {
int a;
int b;
}
static class Data {
HashMap<Key, Integer> map;
}
public static void read() {
Gson gson = new Gson();
String x = "[{\"map\": { \"{\\\"a\\\": 0, \\\"b\\\": 0}\": 1 }}]";
Data[] y = gson.fromJson(x, Data[].class);
}
}
JSON example
[
{
"map": {
"{\"a\": 0, \"b\": 0}": 1
}
}
]
What I would like to achieve here, is that the string "{\"a\": 0, \"b\": 0}" is decoded by GSON to an object of type Key with both members set to 0. Then, that object could be used to fill out the HashMap of the Data class.
Is this possible to achieve?
回答1:
You can achieve this with custom JsonDeserializer. With a custom deserializer you can decide howto deserialize this class Key. Implement it somewhere, inline example below:
public JsonDeserializer<Key> keyDs = new JsonDeserializer<Key>() {
private final Gson gson = new Gson();
@Override
public Key deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context)
throws JsonParseException {
// This will be valid JSON
String keyJson = json.getAsString();
// use another Gson to parse it,
// otherwise you will have infinite recursion
Key key = gson.fromJson(keyJson, Key.class);
return key;
}
};
Register it with GsonBuilder, create Gson and deserialize:
Data[] mapPojos = new GsonBuilder().registerTypeAdapter(Key.class, ds).create()
.fromJson(x, Data[].class);
来源:https://stackoverflow.com/questions/52541220/gson-recursively-decode-map-keys