我一直在使用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)有关,但我不确定此时并且不确定如何解决这个问题......有什么想法吗?
答案 0 :(得分:1)
我没有使用GSon的经验,但未终止的错误通常表示截断或解析器错误(如上所述)。我发现其他人有同样的问题,并鼓励你纠正其他可能的“特殊字符”。在这篇文章org.json.JSONException: Unterminated string at 737 [character 738 line 1]中,问题是&符号。
最诚挚的问候。
答案 1 :(得分:0)
看起来您的服务器发送的响应正在被截断。更改服务器代码可能会有所帮助:
Writer writer = resp.getWriter();
gson.toJson(q.list(), writer);
writer.close();