For JSON I'd suggest using... org.codehaus.jackson
, as it available as play.libs.Json
in Play 2/x
@see: Json Doc
For XML
- template approach is fair enough, as you can render proper XML with the view.
Edit:
Json and Ebean
Sadly must to say that Ebean has a problems with serializing its objects to JSON, therefore I'm always using dedicated inner class (in the target model, which contains only fields, that should be send in Json) ie, for User
model:
public static class ForJson {
public Long id;
public String name;
public String email;
public ForJson(User user) {
this.id = user.id;
this.name = user.name;
this.email=user.email;
}
}
routes:
GET /users/all.json controllers.Application.listUsersJson
GET /users/all-details.json controllers.Application.listUsersJsonWithDetails
GET /users/:id.json controllers.Application.singleUserJson(id: Long)
actions:
public static Result listUsersJson() {
List<User.ForJson> usersToJson = new ArrayList<>();
for (User user : User.find.all()) {
usersToJson.add(new User.ForJson(user));
}
return ok(Json.toJson(usersToJson));
}
public static Result singleUserJson(Long id) {
User.ForJson userForJson = new User.ForJson(User.find.byId(id));
return ok(Json.toJson(userForJson));
}
public static Result listUsersJsonWithDetails() {
Map<String, Object> details = new LinkedHashMap<>();
List<User.ForJson> usersToJson = new ArrayList<>();
for (User user : User.find.all()) {
usersToJson.add(new User.ForJson(user));
}
details.put("date", new Date());
details.put("count", usersToJson.size());
details.put("users", usersToJson);
return ok(Json.toJson(details));
}
Yes, I know maybe it's reduntand coding, but I have at least always proper JSON output, and I don't need to create JSON line by line in each action..
XML:
HTML chars won't break the rendering the proper XML as by default Play's templates escapes them, so instead of <
, >
, "
it will use <
, >
, "
inside the XML node:
<sample>Say "ellou"<sample>
Check Escaping paragraph in templates's doc (bottom of the page).
What's more you can use partial templates - tags to make sure, that single item will be formatted exactly the same in both: users/1.xml
and users/all.xml