Search code examples
jsonplayframeworkplayframework-2.0flexjson

Example on consuming JSON in Play Framework views


I am trying to make the switch in a controller from sending JPA retrieved items as a List to the template engine to now send these as JSON.

I would prefer to use the flexJSON library for the task.

What I have is a Application controller with the method:

public static Result index() {

        ... Processing ...

    flash("success", "Items have been processed");
    return ok(index.render(Item.all()));
}

and a view index.scala.html like this one:

@(items: List[Item])

@import helper._

@main("Item list") {

    <h1>@items.size() items(s)</h1>

    <ul>
        @for(item <- items) {
            <li>
                @item.title                
            </li>
        }
    </ul>
}

These to perfectly show an unnumbered list of all the processed items.

Now, if I changed the controller to using flexJSON like so:

public static Result getItems() {
        List<Item> items = Item.all();

        String s = new JSONSerializer().exclude("*.class", "description").serialize(items);

        flash("success", "Messages have been processed");
        return ok(index.render(s));
    }

How would i program my template in order to consume that json string of items? i tried to follow this blog on the matter, http://www.jamesward.com/2011/12/11/tutorial-play-framework-jpa-json-jquery-heroku, but fall short on how to consume the json in my template views... any code example would be greatly appreciated.


Solution

  • Just Sample it may help you.

    application.conf

    db.default.driver=org.h2.Driver
    db.default.url="jdbc:h2:mem:play"
    ebean.default="models.*"
    

    routes

    GET     /                           controllers.Application.index()
    GET /cities             controllers.Application.all()
    

    Controller => Application.java

    package controllers;
    
    import play.*;
    import play.mvc.*;
    import models.City;
    import play.libs.Json;
    import views.html.*;
    
    public class Application extends Controller {  
    
      public static Result index() {
        return ok(index.render());
      }
    
    
    
        public static Result all(){
    
            City pune=new City();
            pune.name="pune";
            pune.save();
    
            City mumbai=new City();
            mumbai.name="mumbai";
            mumbai.save();
    
            return ok(Json.toJson(City.all()));
          }
    
    
    }
    

    Template => index.scala.html

    <!DOCTYPE html>
    
    <html>
    <head>
    <title>Sample</title>
    <script src="@routes.Assets.at("javascripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
    </head>
    <body>
        <div id="content"></div>
    
        <script type="text/javascript">
    
        $(function(){
            get_cities();       
        });
    
        var get_cities = function() {       
            $.ajax({
                url: '@routes.Application.all()',
                processData:false,
                type: 'GET',
                beforeSend:function(jqXHR, settings){                   
                    jqXHR.setRequestHeader("Content-Type", "application/json");                 
                },
                success: function(data, textStatus, jqXHR){                 
                    process_cities(data);   
                },
                error: function(jqXHR, textStatus, errorThrown){                
                },
                complete: function(jqXHR,textStatus){                   
                }   
            });
        };
    
        var process_cities = function(cities){      
            var contentDiv=$("div#content");
            contentDiv.append("<ul>");            
            $.each(cities,function(i,city){
                contentDiv.append("<li>" + city.name + "</li>");
            });
            contentDiv.append("</ul>");                 
        };
        </script>
    </body>
    </html>