How to make a JSON string on the GWT client side?

Anton Kasianchuk picture Anton Kasianchuk · Jul 24, 2013 · Viewed 9.7k times · Source

I make JSON string on the server side.

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();

That is how I parse that string on the client part.

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;

Now I need to change actions for both sides. I have to encode to JSON on the client and parse it on the server, but I fail to see how I can make a JSON string on the client for it's further parsing on the server. Can I do it with standard GWT JSON library?