1

サーバー側で 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文字列を作成する方法がわかりません。標準の GWT JSON ライブラリで実行できますか?

4

3 に答える 3

5

あなたが使用していてJSONObject JSONVAlueJSONArrayその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()

于 2013-07-24T14:36:18.483 に答える