« Hear Juicy Bits about J6u10 and JavaFX in Java Posse Interview | Main | Let's Create a Tetris Game in Compiled JavaFX Script »

February 21, 2008

Compiled JavaFX Script Now Speaks JSON

As I explained in the XML and JSON Processing post, compiled JavaFX Script has an XML abstraction. It now has a JSON abstraction as well.  I'm sure that there will be tweaks and enhancements to both, but today's example demonstrates how to parse JSON documents.  Here's a screenshot of the application:

Json_example

Go ahead and compile the program, type in an artist, and see the table get populated with the albums from that artist.  As discussed and demonstrated in the Freebase Browser post, the freebase.com server communicates via JSON.  Today's example parses JSON streams from that server as well, sending it the artist name that you enter, and displaying the album titles in a table.  Note that the freebase.com server uses a couple of different ID schemes, so I'll give you a few artists to try:

  • u2
  • the_beatles
  • james_taylor
  • the_rolling_stones
  • the_who
  • norah_jones

Here's the code for the example.  Note: I used a "->" in this example to denote continuing a string on the next line.  When you cut and paste this code into your IDE or text editor, please remove the "->" characters and bring the next line beside that one.  This long line contains the query sent to freebase.com 

/*
*  AlbumsJSON.fx - A compiled JavaFX program that demonstrates
*                  using JSON.
*
*  Developed 2008 by James L. Weaver (jim.weaver at lat-inc.com)
*  to serve as a JavaFX Script example.
*/

import javafx.ui.*;
import javafx.json.*;
import java.lang.Exception;
import java.lang.System;
import java.net.URL;
import java.net.URI;
import java.io.InputStream;

class Model {
  attribute albums:String[];
  private attribute freebaseURL = "http://www.freebase.com/api/service/mqlread?queries=";
  private attribute jsonObj:JSONObject;

  function findAlbums(artist:String):Void {

    var query =
      "\{\"albums\":\{\"query\":\{\"type\":\"/music/artist\", -->
        \"id\":\"/topic/en/{artist}\",\"album\":[]}}}";
    var uri = new URI("http","www.freebase.com", "/api/service/mqlread",
                      "queries={query}", null);
    var url = uri.toURL();

    var p = new Parser();
    jsonObj = p.parse(url.openStream());

    try {
      albums =
      for (albumz in jsonObj.pairs where albumz.name == "albums",
            result in (albumz.value as JSONObject).pairs where result.name == "result",
              album in (result.value as JSONObject).pairs where album.name == "album",
                alb in (album.value as Array).array ) {
          alb.toString();
      }
    }
    catch (e:Exception) {
      MessageDialog {
        title: "Try Again"
        message: "{artist} is not a valid ID for freebase.com"
        visible: true
      }
    }
  }
}

Frame {
  var model = Model {}
  width: 480
  height: 500
  title: "JSON Example"
  background: Color.WHITE
  content:
    BorderPanel {
      center:
        FlowPanel {
          content: [
            Table {
              columns: [
                TableColumn {
                  text: "Album Name"
                }
              ]
              cells: bind for (album in model.albums)
                TableCell {
                  font:
                    Font {
                      size: 16
                    }
                  text: bind "{album}"
                  selected: false
                }
            }
          ]
        }
      bottom:
        FlowPanel {
          var artistTF:TextField
      font:
        Font {
          style: FontStyle.BOLD
          size: 16
        }
          content: [
            SimpleLabel {
              text: "Artist:"
            },
            artistTF = TextField {
              columns: 20
            },
            Button {
              text: "Find Albums"
              defaultButton: true
              action:
                function():Void {
                  model.findAlbums(artistTF.value.toLowerCase())
                }
            }
          ]
        }
    }
  visible: true
  onClose:
    function():Void {
      System.exit(0);
    }
}

Here is the JSON stream returned from freebase.com when you request norah_jones:

{
  "code" : "/api/status/ok",
  "result" : [
    {
      "album" : [
        "First Sessions",
        "Come Away With Me (Limited Edition)",
        "Come Away With Me",
        "Feels Like Home",
        "Feels Like Home (disc 1)",
        "Come Away With Me (bonus disc)",
        "Feels Like Home (bonus disc)",
        "Hamburg 2002 (WDR)",
        "Live In New Orleans",
        "Live in Virginia Beach, Va 7-13-02",
        "Special Norah Jones",
        "Sunrise",
        "Turn Me On",
        "Don't Know Why",
        "Feels Like Home (Deluxe Edition: Disc 1)",
        "Not Too Late",
        "Stay With Me",
        "First Sessions",
        "Not Too Late",
        "New York City"
      ],
      "id" : "/topic/en/norah_jones",
      "type" : "/music/artist"
    }
  ]
}

Parsing in this manner is just one of the features of the JavaFX Script JSON abstraction.  Other features include building a JSON document using object literal syntax, and SAX-like processing of the JSON stream.

JavaFX Script Boot Camp Registration Now Open!

Javafxpertbootcamp300x250bannerindy

I will be offering a 2.5 day JavaFX Script day "boot camp" on Wednesday, April 9 through Friday, April 11, 2008 (ending at noon) in Indianapolis, Indiana.  By the way, I'm scouting out the next location, so if you have suggestions for where I should offer a future BootCamp please let me know!

Regards,
Jim Weaver
JavaFX Script: Dynamic Java Scripting for Rich Internet/Client-side Applications

Immediate eBook (PDF) download available at the book's Apress site

TrackBack

TrackBack URL for this entry:
http://www.typepad.com/services/trackback/6a00e54f133d69883400e550587f898833

Listed below are links to weblogs that reference Compiled JavaFX Script Now Speaks JSON:

Comments

Get the best out os the best by going to http://w-aw.com , get WareZ for free, just search, or go to one of the topics and get that thing. Its ALL FREE! Scripts like Able Dating 2.4 NULLED! is NOW! available. Also the latest version of vBulletin and mods are now available. WaW Info :- 14000+ FREE SCRIPTS, 3400+ FREE TEMPLATES, 9000+ FREE COMPONENTS, 1000+ FREE MOVIES, 1800+ FREE TOOLS, 7400+ FREE ICONS, 3200+ FREE SONGS, 16000+ FREE APPLICATIONS, 70000 NEWS REPORT, 1900 SEO TOOLS, 8000 GAMES FOR PC, PS2/3, XBOX, XBOX LIVE, MOBILE, PSP AND LOADS MORE. http://w-aw.com

good article.

Verify your Comment

Previewing your Comment

This is only a preview. Your comment has not yet been posted.

Working...
Your comment could not be posted. Error type:
Your comment has been posted. Post another comment

The letters and numbers you entered did not match the image. Please try again.

As a final step before posting your comment, enter the letters and numbers you see in the image below. This prevents automated programs from posting comments.

Having trouble reading this image? View an alternate.

Working...

Post a comment

My Photo

Upcoming Speaking Engagements:


  • Stephen Chin and Jim Weaver speaking about JavaFX Platform

  • Speaking on JavaFX and Java at Øredev in Malmö, Sweden on 2-6 November, 2009

Upcoming JavaFX Training:


  • Developing Secure, Rich Internet Applications Hosted on a Variety of Clients Using JavaFX Technology

Enter your email address:

Delivered by FeedBurner

Available now as early access eBook


  • Click book image above to obtain eBook

Twitter Updates

    follow me on Twitter

    Affiliations:

    DZone Links:


    July 2009

    Sun Mon Tue Wed Thu Fri Sat
          1 2 3 4
    5 6 7 8 9 10 11
    12 13 14 15 16 17 18
    19 20 21 22 23 24 25
    26 27 28 29 30 31  

    Disclaimer:

    • By reading this site, you are agreeing that under no circumstances will Veriana Networks, Inc. or its affiliates be responsible for (1) any information contained on or omitted from the site, (2) any person's reliance on any such information, whether or not the information is correct, current or complete, (3) the consequences of any action you or any other person takes or fails to take, whether or not based on information provided by or as a result of the use of the sites.