Converting Action Script object to XML

The Flex and XML Portlet is sample of how you can send XML String from Java Portlet to Flex and Flex displays it in DataGrid format. In that blog i covered how to submit data entered by user in Flex application, using HTTP POST method.






I changed the Sample code so that now i am converting the data submitted by user in Flex application into XML first then submitting it using HTTP POST method. I am using As3xml library for converting Action Script object into XML.

In order to get this sample working first i had to define Flex Contact class then change the addContact() method like this

public function addContact():void{
trace("Entering useHttpService");
service = new HTTPService();
service.url = nextActionURL;
service.resultFormat = HTTPService.RESULT_FORMAT_TEXT;
service.method = "POST";
var myContact:Contact = getContact();

var myContactXML:XML= Asx3mer.instance.toXML(myContact);

var params:Object = { myContactStr: myContactXML };

service.send(params);
getContactList();
trace("Entering useHttpService");
}
public function getContact():Contact{
var myContact:Contact =new Contact();
myContact.firstName = txtFirstName.text;
myContact.lastName = txtLastName.text;
myContact.email = txtEmail.text;
return myContact;
}


First i did create a getContact() method which reads values entered by user in Flex application and returns a Contact object based on it. Then converting Contact Flex object into XML object is pretty simple all i had to do was call Asx3mer.instance.toXML(). What i liked most is about working with XML in Flex is how easy it is pretty print XML, all i had to do was print the XML object and it prints a XML like this


<com.webspherenotes.flex.Contact>
<firstName>Sachin</firstName>
<lastName>Tendulkar</lastName>
<email>sachin@mi.com</email>
</com.webspherenotes.flex.Contact>


I am submitting a form to the actionURL with this XML as value of myContactStr

Then on the server side i had to create a method which can parse the XML string into Java Object, i am using Xstream for that

public static Contact convertXMLToJava(String xmlStr){
XStream xstream = new XStream(new DomDriver());
xstream.setMode(XStream.NO_REFERENCES);
xstream.alias("com.webspherenotes.flex.Contact", Contact.class);
System.out.println("setting values of contact object");
Contact contact= (Contact)xstream.fromXML(xmlStr);
return contact;
}

2 comments:

Unknown said...

I have unbox so many company like nokia lenove etc if you want to unbox something ask me

Abhi said...

Thanks for info....
SEO Company in Bangalore