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?
You are using JSONObject
JSONVAlue
and JSONArray
whose toString()
method should give you a well formed json representation of your object.
See :
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()