views:

152

answers:

2

I'm new to Play Framework, and having trouble rendering a JSON object.

public static void LoginFail() {

 Object[][] statusArray = {

   {"Status", "401"},
   {"Message", "Unauthorized"},
         {"Detail", "No API Key Supplied"}

    };



 renderJSON(statusArray);

}

This only displays "[[{},{}],[{},{}],[{},{}]]"...what am I doing wrong? I can't find any solid documentation on this. I tried configuring the route for Application.LoginFail(format:'json'), but this did nothing.

+2  A: 

From the looks of your code it seems that your are trying the create a JSON string by yourself, using an array of type Object. My only guess as to why this doesn't work is that GSON (the JSON library in use by play) doesn't know how to convert that to key-value pairs (although your array is 2-dimensional). So how about changing statusArray to String and its content to:

{
    "Status": "401",
    "Message": "Unauthorized",
    "Detail": "No API Key Supplied"
}

Put that into renderJSON(statusArray) and you should be fine.

As an alternative you could create a simple .json template like the following:

{
    "Status": ${status},
    "Message": ${message},
    "Detail": ${detail}
}

and call it from a controller method via render(status, message, detail). status, message and detail being Strings here as well. Example controller method:

public static void loginFail(final String status, final String message, final String detail) {
    render(status, message, detail);
}

and your template would be called loginFail.json (the name of the controller method). That way you can call the controller method in whatever logic you have to verify the login. Once the login fails you specify why that is (via status, message and details) by calling the loginFail method.

seb
A: 

Do it the simple & reusable way by creating a StatusMessage object

public class StatusMessage {
   public String status;
   public String message;
   public String detail;

   public StatusMessage(String status, String message, String detail) [
      this.status = status;
      this.message = message;
      this.detail = detail;
   }
}

And then

renderJSON(new StatusMessage("401", "Unauthorized", "No API Key Supplied"));
Damo