I would like to use this kind of Objects with json:
class Message{
int code;
String user;
Map<List<String>, List<String>> profile;
}
it seems json can't handle Object keys as array, so I would need to tranfer them like that:
{
"code": 1,
"user": "John",
"profile": {
"type,1": ["tester"],
"lang,2": ["fr", "it", "en", "sp"],
"rate,4": ["10", "1000"],
"date,5": ["134118329", "1341973211"]
}
}
or
{
"code": 1,
"user": "John",
"profile": {
"type": [1,"tester"],
"lang": [2,"fr", "it", "en", "sp"],
"rate": [4,"10", "1000"],
"date": [5,"134118329", "1341973211"]
}
}
the first json is probably simpler, even if it relies on a hard string separator,
So with the first one it seems I have to write this huge adapter:
private static class MyAdapter implements JsonSerializer<Map<List<String>, List<String>>>,
JsonDeserializer<Map<List<String>, List<String>>> {
@Override
public JsonElement serialize(Map<List<String>, List<String>> m,
Type type, JsonSerializationContext context) {
JsonObject j = new JsonObject();
for (Entry<List<String>, List<String>> e : m.entrySet() ){
JsonArray jj=new JsonArray();
for (String s : e.getValue()){
jj.add(new JsonPrimitive(s));
}
j.add(e.getKey().get(0)+","+e.getKey().get(1), jj);
}
return j;
}
@Override
public Map<List<String>, List<String>> deserialize(JsonElement json, Type type,
JsonDeserializationContext arg2) throws JsonParseException {
Map<List<String>, List<String>> m = new HashMap<List<String>, List<String>>();
JsonObject jObject = json.getAsJsonObject();
for (Entry<String, JsonElement> e : jObject.entrySet() ){
List<String> key = new ArrayList<String>();
List<String> value = new ArrayList<String>();
for (String s : e.getKey().split(",") ){
key.add(s);
}
for (JsonElement jj : e.getValue().getAsJsonArray() ){
value.add(jj.getAsString());
}
m.put(key, value);
}
return m;
}
}
...
GsonBuilder g = new GsonBuilder();
g.registerTypeAdapter(Map.class, new MyAdapter());
Gson gson = g.create();
Is there faster ways? I guess yes, the idea is just to split the key into a Map composite key, because each part of the key has an important meaning
thx, and sry for the edit