Stas
Stas

Reputation: 1365

Play! Framework return json response

I`m using Play! Framework 2.0 and I'm new in this framework. How can I return just a json representation of my model in white html page?

What I'm doing is

public static void messagesJSON(){  
   List<Message> messages = Message.all();  
   renderJSON(messages);  
}

But I get Error : Cannot use a method returning Unit as an Handler

Upvotes: 11

Views: 26219

Answers (3)

Connor Leech
Connor Leech

Reputation: 18833

Create a new Model from your list:

public static Result getBusinesses(){
    List<Business> businesses = new Model.Finder(String.class,  Business.class).all();
    return ok(Json.toJson(businesses));  //displays JSON object on empty page
}

In the Business.java class I have a static variable:

public static Finder<Long,Business> find = new Finder(Long.class, Business.class);

This will display the JSON object on localhost:9000/getBusinesses after you add the route:

GET      /getBusinesses   controllers.Application.getBusinesses()

Upvotes: 2

Sudhir
Sudhir

Reputation: 736

How about return ok(Json.toJson(Moments.all());

Upvotes: 41

Codemwnci
Codemwnci

Reputation: 54884

The method you are using is from Play 1.x, it is slightly different in Play 2.0. From the documentation, here is an example of how to reply to a sayHello JSON request

@BodyParser.Of(Json.class)
public static Result sayHello() {
  ObjectNode result = Json.newObject();
  String name = json.findPath("name").getTextValue();
  if(name == null) {
    result.put("status", "KO");
    result.put("message", "Missing parameter [name]");
    return badRequest(result);
  } else {
    result.put("status", "OK");
    result.put("message", "Hello " + name);
    return ok(result);
  }
}

The important part of this from what you are asking is the return ok(result) which returns a JSON ObjectNode.

Upvotes: 12

Related Questions