Jim has posted 66 posts at DZone. You can read more from them at their website. View Full User Profile

Compiled JavaFX Script Now Speaks JSON

02.21.2008
| 7734 views |
  • submit to reddit

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.

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

Published at DZone with permission of its author, Jim Weaver.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags:

Comments

mudit sharma replied on Wed, 2008/09/24 - 9:44am

javafx.json package seems to have been removed. Could u please tell new location of corresponding file

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.