Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does play.libs.Json.fromJson handled a List<T> in Java?

I'd like to use the Json library that comes with the play 2.1 framework. But I'm stuck with deserializing a json object back into a java List.

With gson, you can write s.th. like

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 appreciated.

Edit (17.12.2013):

I did the following to work around the problem. I guess there is a better way, but I didn't 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;
like image 450
Wintermute Avatar asked Jun 17 '13 19:06

Wintermute


1 Answers

The Json library for Play Java is really just a thin wrapper over the Jackson JSON library (http://jackson.codehaus.org/). The Jackson way to deserialize a list of custom objects is mentioned here.

For your case, once you parse the json from the response body, you would do something like this, assuming MyObject is a plain POJO:

JsonNode json = res.asJson();
try{
    List<MyObject> objects = new ObjectMapper().readValue(json, new TypeReference<List<MyObject>>(){});
}catch(Exception e){
    //handle exception
}

I'm assuming you were asking about Play Java based on your edit, Play Scala's JSON library is also based on Jackson but has more features and syntactic sugar to accommodate functional programming patterns.

like image 134
josephpconley Avatar answered Sep 19 '22 03:09

josephpconley