サーバー側でJSON文字列を作成します。
JSONObject responseObject = new JSONObject();
List<JSONObject> authorList = new LinkedList<JSONObject>();
try {
for (Author author : list) {
JSONObject jsonAuthor = new JSONObject();
jsonAuthor.put("name", author.getName());
jsonAuthor.put("surname", author.getSurname());
authorList.add(jsonAuthor);
}
responseObject.put("authors", authorList);
} catch (JSONException ex) {
ex.printStackTrace();
}
return responseObject.toString();
これが、クライアント部分でその文字列を解析する方法です。
List<Author> auList = new ArrayList<Author>();
JSONValue value = JSONParser.parse(json);
JSONObject authorObject = value.isObject();
JSONArray authorArray = authorObject.get("authors").isArray();
if (authorArray != null) {
for (int i = 0; i < authorArray.size(); i++) {
JSONObject authorObj = authorArray.get(i).isObject();
Author author = new Author();
author.setName(authorObj.get("name").isString().stringValue());
author.setSurname(authorObj.get("surname").isString().stringValue());
auList.add(author);
}
}
return auList;
今、私は双方の行動を変える必要があります。クライアントでJSONにエンコードしてサーバーで解析する必要がありますが、サーバーでさらに解析するために、クライアントでJSON文字列を作成する方法がわかりません。標準のGWTJSONライブラリでそれを行うことはできますか?
あなたが使用していてJSONObject
JSONVAlue
、JSONArray
そのtoString()
メソッドがあなたのオブジェクトの整形式のjson表現を与えるはずです。
見る :
http://www.gwtproject.org/javadoc/latest/com/google/gwt/json/client/JSONObject.html#toString()
http://www.gwtproject.org/javadoc/latest/com/google/gwt/json/client/JSONValue.html#toString()
http://www.gwtproject.org/javadoc/latest/com/google/gwt/json/client/JSONArray.html#toString()
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加