Play! Framework return json response

24,801

Solution 1

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.

Solution 2

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

Solution 3

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()
Share:
24,801
Stas
Author by

Stas

Updated on July 09, 2022

Comments

  • Stas
    Stas almost 2 years

    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

  • Stas
    Stas almost 12 years
    What does it mean "index" as a return type? It seems to me that compiler do not understand it, @BodyParser also error (type mismatch) does this code works for you? Or could you show imports and more broader picture of veriables.
  • biesior
    biesior almost 12 years
    @Stas, there was a typo in source docs, it should return Result as every action in Play 2.0 controller.
  • Codemwnci
    Codemwnci almost 12 years
    Good spot @Marcus. And thanks for updating the documentation on Github as well.
  • prule
    prule almost 11 years
    This is a much more useful answer since it will automatically render the whole object graph into json - rather than having to manually build json objects as shown in the documentation.
  • riley chen
    riley chen almost 11 years
    I believe you can customize the JSON structure as well via Jackson annotations.
  • Alex
    Alex about 10 years
    Add a class reference:
  • riley chen
    riley chen about 10 years
    import play.libs.Json @Alex ?
  • kn3l
    kn3l almost 8 years
    Ok not ok first uppercase O.