Micky Micky - 3 months ago 18
Java Question

Play Java, How to read a local JSON file and show as list on a body?

I am starting learning Play Java, and found many different samples (often without imports etc.) about how to do what explained on subject.
I am using Play 2.5 and JDK 8, and configured my own controller. The file is in a directory that I can access from the controller Java class, but not clear to me what is the best practice to read the JSON file: through Jackson? or java.io.* functions?
Is it possible to obtain a working minimal sample from an expert?
I tried following this guide, but the code goes always in error (sample code does't neither have the final comma!):
https://www.playframework.com/documentation/2.5.x/JavaJsonActions

Basically my json items.json is under ..workspace\play-java\app\data\items.json .

The JSON file is something like this:
[
{
"id": 10000000,
"name": "name1",
"starttime": "2015-06-18T06:26:56-07:00",
"endtime": "2015-07-08T12:47:16-07:00"
}, etc.
]

and I guess that in the function to read the file I need to specify the path 'app/data/items.json' or 'data/items.json'

Thanks in advance!

Answer

If you want to deliver JSON to the client, you can use the Json class to convert an input stream (or string) into a JsonNode and pass that directly back in the response. Because you're using a JsonNode, the content type of the will be response will be set automatically.

(For this example, I created a file in /conf called foo.json.)

package controllers;

import java.io.IOException;
import java.io.InputStream;
import javax.inject.Inject;
import com.fasterxml.jackson.databind.JsonNode;
import play.Environment;
import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Result;

public class SomeController extends Controller {

    private final Environment env;

    @Inject
    public SomeController(final Environment env) {
        // the environment is used to access local files
        this.env = env;
    }

    public Result index() {
        try (InputStream is = env.resourceAsStream("/foo.json")) {
            final JsonNode json = Json.parse(is);
            return ok(json);
        } catch (IOException e) {
            return internalServerError("Something went wrong");
        }
    }
}
Comments