我想将这种对象与 json 一起使用:
class Message{
int code;
String user;
Map<List<String>, List<String>> profile;
}
似乎 json 无法将 Object 键作为数组处理,所以我需要像这样传输它们:
{
"code": 1,
"user": "John",
"profile": {
"type,1": ["tester"],
"lang,2": ["fr", "it", "en", "sp"],
"rate,4": ["10", "1000"],
"date,5": ["134118329", "1341973211"]
}
}
或者
{
"code": 1,
"user": "John",
"profile": {
"type": [1,"tester"],
"lang": [2,"fr", "it", "en", "sp"],
"rate": [4,"10", "1000"],
"date": [5,"134118329", "1341973211"]
}
}
第一个 json 可能更简单,即使它依赖于硬字符串分隔符,
因此,对于第一个,我似乎必须编写这个巨大的适配器:
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();
有更快的方法吗?我猜是的,思路就是把key拆分成一个Map组合key,因为key的每一部分都有重要的意义
谢谢,很抱歉编辑