我一直在使用 Gson 将 json 对象从 appengine 传输到我的 android 客户端,没有问题。我正在使用下面的代码。
服务器:
Query<WaterSupply> q = ofy.query(WaterSupply.class).filter("FdID", fdID)
.filter("timeUpdated >", lastUpdate);
Gson gson=new Gson();
resp.getWriter().print(gson.toJson(q.list()));
客户:
List<WaterSupply> list=new ArrayList<WaterSupply>();
String json1 =wsResult.wsResponse;
JsonElement json = new JsonParser().parse(json1);
JsonArray array= json.getAsJsonArray();
Iterator<JsonElement> iterator = array.iterator();
while(iterator.hasNext()){
JsonElement json2 = (JsonElement)iterator.next();
Gson gson = new Gson();
WaterSupply ws= gson.fromJson(json2, WaterSupply.class);
//can set some values in contact, if required
list.add(ws);
}//Unable to invoke no-args constructor for interface com.jackson.FirefighterLog.shared.WaterSupplyProxy.
//Register an InstanceCreator with Gson for this type may fix this problem.
Gson gson = new Gson();
Type listType = new TypeToken<List<WaterSupply>>(){}.getType();
List<WaterSupply> wsList = (List<WaterSupply>) gson.fromJson(wsResult.wsResponse, listType);
我已经开始使用更大的对象并且不得不切换到流解析实现,因为我遇到了内存不足的错误。我现在正在使用以下代码:
服务器:同上
客户:
public static List<WaterSupply> readJsonStream(InputStream in) throws IOException {
JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
Gson gson=new Gson();
List<WaterSupply> messages = new ArrayList<WaterSupply>();
reader.beginArray();
while (reader.hasNext()) {
WaterSupply message = gson.fromJson(reader, WaterSupply.class);
messages.add(message);
}
reader.endArray();
reader.close();
return messages;
}
我假设这与换行符(/ n)有关,但我现在不确定,也不知道如何解决这个问题......有什么想法吗?