Using JSON Templates in Play 2.0

I get this error:

Compilation error [package views.json.Runs does not exist]

when it clearly exists. I can’t understand what I can do wrong.

action in the Runs controller:

 @BodyParser.Of(play.mvc.BodyParser.Json.class) public static Result view(Long task_id, Long run_id) { Run run = Run.find.byId(run_id); return ok(views.json.Runs.view.render(run)); } 

app/views/Runs/view.scala.json :

 @(run: Run) { "started": "@run.started", "completed": "@run.completed" } 

I got some html templates, but this is the first JSON template I tried with 2.0. I'm not sure what else to try, as this is already possible as thoroughly as possible. Does anyone have any ideas?

Update . I came up with a few suggestions on workarounds, but I'm still interested in learning how to make the templates work if I only better understand the 2.0 changes.

+6
source share
4 answers

By default, only html, xml and txt are supported. For other extensions and file formats, you will need to register additional “type templates” in $PLAY_HOME/framework/src/sbt-plugin/src/main/scala/PlaySettings.scala (see Also: SBT Settings , below).

It may be useful to look at the definitions of the standard template types, which are located in $PLAY_HOME/framework/src/play/src/main/scala/play/api/templates/Templates.scala .

You can also spoof and serve json from a txt file, but response().setContentType("application/json") before calling the render method.

+7
source

For Json, why don't you directly create a Json string using the Json helper :

 public static Result view(Long task_id, Long run_id) { Run run = Run.find.byId(run_id); return ok(play.libs.Json.toJson(run)); } 
+3
source

I recommend following the documentation and letting the Json library serialize your data instead of writing Json text yourself: See "Json Response Services" .

+2
source

I still don't understand why people want to display their JSON with views.

Note: this is the same as shown in @nico_ekito, and I completely agree with it, the code below simply demonstrates how to select a part of the object for JSON

 public static Result view(Long task_id, Long run_id){ Run run = Run.find.byId(run_id); ObjectNode result = Json.newObject(); result.put("started", run.started); result.put("completed", run.completed); return ok(Json.toJson(result)); } 
0
source

Source: https://habr.com/ru/post/919352/


All Articles