|
JavaFX provides all the tools necessary for server communication. Two main classes used to exchange
data between JavaFX client and server are HTTPRequest class to send and receive data and a
PullParser to parse the incoming XML or JSON data.
But what we need is a DataMapper utility to convert JavaFX object to XML or JSON string that can be sent to
the server and a function to initialize a JavaFX objects from XML or JSON strings receiving from the server.
In this artical we will discuss how to build the dataMapper utility.
Say we have a Person class in our applicaiton:
class Person {
var firstName:String;
var lastName:String;
var age: Integer;
var isStudent : Boolean;
}
and the instance of a class:
var person = Person {
firstName:"John"
lastName: "Doe"
age: 20
isStudent: true
}
To send this object to server, we need to create the followign JSON String:
{"firstName" : "John", "lastName" : "Doe", "age": 20, "isStudent": true }
The server could similar JSON string and we would like to iniatilize JavaFX object using the data in the string.
Our DataMapper utility class can be defined as follows:
class DataMapper {
var dataString : String; //JSON data
var fxObject : Object; // JavafX object
function initFx(): Void; //Initialize fxObject from dataString
function toJson() : String; // Create JSON string from fxObject
}
To create a JSON string, we create a DataMapper class and call the toJson method as follows:
var mapper : DataMapper = DataMapper {
fxObject: person;
}
var jstring: String = mapper.toJson(); //create JSON string
To initialize JavaFX object , we create a DataMapper object and call the initFx() method as follows:
var person : Person = Person {}; //Empty JavaFX object
var jsonData = "\{ \"firstName\":\"John\", \"lastName\":\"Doe\", \"age\":10, \"isStudent\":true \}";
var mapper : DataMapper = DataMapper {
dataString: jsonData;
fxObject: person; //object to be initialized
}
mapper.initFx(); //Initialize fx object
The code below shows the DataMapper uitility. The tutorials explain the details of how reflectino API work.
|