Вопрос

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?

Это было полезно?

Другие советы

I recommend you to take a look at the GWT AutoBean framework. It allows you to send objects through the network and do not touch JSON directly. The code becomes shorter.

That is what I did:

List<Author> auList = new ArrayList<Author>();
JSONObject authorObject = new JSONObject(json);
JSONArray authorArray = authorObject.getJSONArray("authors");
if (authorArray != null) {
    for (int i = 0; i < authorArray.length(); i++) {
        JSONObject authorObj = authorArray.getJSONObject(i);
        Author author = new Author();
        author.setName((String) authorObj.getString("name"));
        author.setSurname((String) authorObj.getString("surname"));
        auList.add(author);
    }
}
return auList;

The problem was I didn't know how to use JSONArray properly.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top