我使用GsonRequest来序列化我的数据。但是我有这种情况:
这是JSON中的数据:
[...]
"u": {
"53bde5b5e4fc4978c0000015": {
"la": 40.772673,
"lo": 9.6657388
}, ...
我用以下数据序列化数据:
public class ClusterResult extends SingleElement{
public Integer count;
public ClusterData[] c;
public HashMap<String, ClusterUnit> u;
}
(与Map相同)
知道如何改变吗?我使用GsonRequest类来序列化数据(https://gist.github.com/ficusk/5474673)。
谢谢:)
答案 0 :(得分:0)
为什么不尝试将ClusterUnit
包装在一个类中并使用自定义反序列化器?也许我不知道你的问题是什么,如果是这样,请告诉我。我就这样做了:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import java.lang.reflect.Type;
import java.util.Map;
/**
*
* @author astinx
*/
public class Test {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Test().run();
}
public class ClusterUnitWrapped {
String id; //53bde5b5e4fc4978c0000015
Double la;
Double lo;
private ClusterUnitWrapped(String id, Double la, Double lo) {
this.id = id; this.la = la; this.lo = lo;
}
@Override
public String toString() {
return "ClusterUnitWrapped{" + "id=" + id + ", la=" + la + ", lo=" + lo + '}';
}
}
public class ClusterUnitRequest {
//...
ClusterUnitWrapped u;
//...
@Override
public String toString() {
return "ClusterUnitRequest{" + "u=" + u + '}';
}
}
private class ClusterUnitDeserializer implements JsonDeserializer<ClusterUnitWrapped> {
public ClusterUnitWrapped deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
for (Map.Entry<String, JsonElement> map : json.getAsJsonObject().entrySet()) {
String id = map.getKey().toString(); //Obviously is going to iterate only once.
Double la = map.getValue().getAsJsonObject().get("la").getAsDouble();
Double lo = map.getValue().getAsJsonObject().get("lo").getAsDouble();
return new ClusterUnitWrapped(id, la, lo);
}
return null;
}
}
private void run() {
String json = "{\"u\":{\"53bde5b5e4fc4978c0000015\": { \"la\": 40.772673, \"lo\":9.6657388}}}";
Gson gson = new GsonBuilder()
.registerTypeAdapter(ClusterUnitWrapped.class, new ClusterUnitDeserializer())
.create();
ClusterUnitRequest u = gson.fromJson(json, ClusterUnitRequest.class);
System.out.println(u.toString());
}
}