How does play.libs.Json.fromJson handle List <T> in Java?
I would like to use the Json library that comes with the play 2.1 framework. But I am stuck in deserializing a json object back to a Java list.
Using gson you can write s.th. as
Type type = new TypeToken<List<XYZ>>(){}.getType(); List<XYZ> xyzList = gson.fromJson(jsonXyz, type); Is there a way to do the same with play.libs.Json.fromJson?
Any help was appreciated.
Edit (12/17/2013):
To solve this problem, I did the following. I think there is a better way, but I have not found it.
List<MyObject> response = new ArrayList<MyObject>(); Promise<WS.Response> result = WS.url(Configuration.getRestPrefix() + "myObjects").get(); WS.Response res = result.get(); JsonNode json = res.asJson(); if (json != null) { for (JsonNode jsonNode : json) { if (jsonNode.isArray()) { for (JsonNode jsonNodeInner : jsonNode) { MyObject mobj = Json.fromJson(jsonNodeInner, MyObject.class); response.add(bst); } } else { MyObject mobj = Json.fromJson(jsonNode, MyObject.class); response.add(bst); } } } return response; The Json library for Play Java is a really thin shell of the Jackson JSON library ( http://jackson.codehaus.org/ ). The Jackson way of deserializing a list of user objects is mentioned here .
In your case, once you parsed json from the response body, you would do something like this, assuming MyObject is a simple POJO:
JsonNode json = res.asJson(); try{ List<MyObject> objects = new ObjectMapper().readValue(json, new TypeReference<List<MyObject>>(){}); }catch(Exception e){ //handle exception } I assume that you asked about Play Java based on your editing, the Play Scala JSON library is also based on Jackson, but has more features and syntactic sugar to accommodate functional programming patterns.