Welcome!

Java IoT Authors: Elizabeth White, Pat Romanski, Yeshim Deniz, Liz McMillan, Paul Simmons

Related Topics: Java IoT, Open Source Cloud

Java IoT: Article

JSON Serialization with Appcelerator Java Services

Serializing/transforming model objects is really easy to do with Appcelerator IModelObjects

The issue of serializing/transforming model objects is not new, heck I’ve been doing this for quite some time:

  • RMI (ejb/corba)
  • XML (jms, soap, etc..)
  • JSON 
JSON is not the only way to serialize objects for Web 2.0 applications, but it's the most abundant and heavily used throughout the Appclerator framework. Doing this is actually really easy to do with Appcelerator IModelObjects. Our IModelObjects can easily be used along with Hibernate for persistance, but let's leave that for later for now.

When you define your Model classes, there are some very simple things to keep in mind:
  • annotate your attributes with @MessageAttr
  • have your class implement IModelObject

Here is a simple example:

<public class User implements IModelObject, Serializable {
private static final long serialVersionUID = 1L;
@MessageAttr
public String name;

public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
...
}

Unit test it

Now to test the rendering of our object to JSON with a simple junit test…. As you can see, we leverage the Appcelerator framework to serialize our objects to JSON

public class ForumTest extends TestCase {
 
public void testSimple() {
User user = createUser();
Message message = new Message();
JSONMessageDataObject data = new JSONMessageDataObject();
message.setData(data);
message.getData().put("user", user);
message.getData().put("count", 1);
String messagestr = data.toDataString();
assertEquals(messagestr,"\"user\":{\"password\":
\"pwd\",\"threads\":0,\"fullName\"
:\"antewew\",\"username\":\"azuercher\",\"state\":
\"mystate\",\"email\":\"email\",
\"posts\":0,\"id\":0},\"count\":1}");
}
private User createUser() {
User user = new User();
user.setEmail("email");
user.setFullName("ante wew");
user.setId(new Long(0));
user.setPassword("pwd");
user.setPosts(new Long(0));
user.setState("mystate");
user.setThreads(new Long(0));
user.setUsername("azuercher");
return user;
}
}

Dealing with recursion

Whats always a bit of a tangle is understanding how to deal with the recursive/circular relationship.
If you take a look at JSONObject you will see 2 overridden methods for createBean

public static JSONObject createBean(IModelObject object,MessageAttr
    parentAtt, String context,String[] parentSuppres,int level, int maxlevels)
public static JSONObject createBean(IModelObject object)

The latter is obviously a bit more simple, but the former is where the power is. In the MessageAttr annotation, you can provide the suppress attribute which is a comma separated list of aggregates (using bean.name notation to not serialize). This is used for attributes in your IModelObject implementation where the association is with another IModelObject. The following model is for a forum object model where the following aggregate hierarchy exists:

* Forum
** ForumThread
*** Post

In the snippet below, I’ve omitted the getter/setter methods for the aggregates for simplicity.

public class User implements IModelObject, Serializable {
@MessageAttr (suppress="user,thread.lastPost")
public Post lastPost;
}
public class Post implements IModelObject, Serializable {
@MessageAttr(suppress="lastPost,forum.lastPost")
public Forumthread thread;
 
@MessageAttr (suppress="lastPost")
public User user;
}
public class Forumthread implements IModelObject, Serializable {
@MessageAttr (suppress="lastPost")
public Forum forum;
@MessageAttr (suppress="thread,user.lastPost")
public Post lastPost;
}
public class Forum implements IModelObject, Serializable {
@MessageAttr (suppress="thread.forum,thread.lastPost,user.lastPost")
public Post lastPost;
}

Rolling your own serialization

Assuming you know what your JSON string is going to look like, you can use our RawMessageDataList and RawMessageDataObject to serialze your objects. This is pretty useful if you already are rendering JSON in an existing framework and don’t want to have to transform to and back again. The snippet below shows with static strings just so that you get the idea:

IMessageDataList people = new
RawMessageDataList(
"[{'name':'joe','age':22},{'name':'jane','age':33}]");
IMessageDataList dog = new RawMessageDataObject("{'breed':'doberman','weight':78}");
Message message = new Message();
message.setData(new JSONMessageDataObject());
message.getData().put("people", people);
message.getData().put("dog", dog);

Using Coarse Grained objects

This is probably the simplest/prettiest way to implement your services assuming that you aren’t interested in using fine grained classes that are associated with most of today’s persistence frameworks. Here is how you would create a single compound JSON object:

IMessageDataObject dog =
MessageUtils.createMessageDataObject();
obj.put("breed","doberman");
obj.put("wieght",78);Message message = new Message();
message.setData(new JSONMessageDataObject());
message.getData().put("dog", dog);

and now with a collection:

IMessageDataList&lt;IMessageDataObject&gt; people=
MessageUtils.createMessageDataObjectList();
IMessageDataObject joe =
MessageUtils.createMessageDataObject();
joe.put("name","joe");
joe.put("age",22);
IMessageDataObject jane =
MessageUtils.createMessageDataObject();
joe.put("name","jane");
joe.put("age",33);
people.put(joe);
people.put(jane);
Message message = new Message();
message.setData(new JSONMessageDataObject());
message.getData().put("people", people);

Summary

As you can see there are quite a bit of alternatives for you based on what your needs are to accommodate your service implementations. I’ve personally used all of the above as I’ve implemented:

  • Model Objects: using Hibernate for persistence
  • Custom Serialization: for integrating with pre-rendered objects (commons-monitoring)
  • Coarse Grained: in implementing a dashboard/event driven solution

More Stories By Andrew Zuercher

Andrew Zuercher is an Enterprise Architect at Appcelerator, advocating the implementation of RIA with agile methodologies.

Comments (3) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
Duty Editor 02/18/08 12:10:16 PM EST

No problem Andrew, we've taken cxare of it.

andrew zuercher 02/18/08 11:04:17 AM EST

to dove tail on the feedback that i left last friday, i was wondering if you could corect the reference to http://zuerchtech.com instead of http://zuerchertech.com which is not associated with me whatsoever.

much thanks,

-andrew zuercher

Andrew Zuercher 02/15/08 07:21:51 PM EST

Thanks for publishing this article which is also cross posted at:
* http://www.appcelerant.com/json-serialization-with-appcelerator-java-ser...
* http://zuerchtech.com/2008/2/8/json-serialization-with-appcelerator-java...

Please note, that although I ran Zuercher Technologies based out of Atlanta, GA I have since dissolved it and now am employed at Appcelerator (http://appcelerator.com) as an Enterprise Architect advocating the implementation of RIA with agile methodologies.

@ThingsExpo Stories
"MobiDev is a software development company and we do complex, custom software development for everybody from entrepreneurs to large enterprises," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Major trends and emerging technologies – from virtual reality and IoT, to Big Data and algorithms – are helping organizations innovate in the digital era. However, to create real business value, IT must think beyond the ‘what’ of digital transformation to the ‘how’ to harness emerging trends, innovation and disruption. Architecture is the key that underpins and ties all these efforts together. In the digital age, it’s important to invest in architecture, extend the enterprise footprint to the cl...
Data is the fuel that drives the machine learning algorithmic engines and ultimately provides the business value. In his session at Cloud Expo, Ed Featherston, a director and senior enterprise architect at Collaborative Consulting, discussed the key considerations around quality, volume, timeliness, and pedigree that must be dealt with in order to properly fuel that engine.
Two weeks ago (November 3-5), I attended the Cloud Expo Silicon Valley as a speaker, where I presented on the security and privacy due diligence requirements for cloud solutions. Cloud security is a topical issue for every CIO, CISO, and technology buyer. Decision-makers are always looking for insights on how to mitigate the security risks of implementing and using cloud solutions. Based on the presentation topics covered at the conference, as well as the general discussions heard between sessio...
IoT is rapidly becoming mainstream as more and more investments are made into the platforms and technology. As this movement continues to expand and gain momentum it creates a massive wall of noise that can be difficult to sift through. Unfortunately, this inevitably makes IoT less approachable for people to get started with and can hamper efforts to integrate this key technology into your own portfolio. There are so many connected products already in place today with many hundreds more on the h...
No hype cycles or predictions of zillions of things here. IoT is big. You get it. You know your business and have great ideas for a business transformation strategy. What comes next? Time to make it happen. In his session at @ThingsExpo, Jay Mason, Associate Partner at M&S Consulting, presented a step-by-step plan to develop your technology implementation strategy. He discussed the evaluation of communication standards and IoT messaging protocols, data analytics considerations, edge-to-cloud tec...
Announcing Poland #DigitalTransformation Pavilion
Digital Transformation is much more than a buzzword. The radical shift to digital mechanisms for almost every process is evident across all industries and verticals. This is often especially true in financial services, where the legacy environment is many times unable to keep up with the rapidly shifting demands of the consumer. The constant pressure to provide complete, omnichannel delivery of customer-facing solutions to meet both regulatory and customer demands is putting enormous pressure on...
CloudEXPO | DXWorldEXPO are the world's most influential, independent events where Cloud Computing was coined and where technology buyers and vendors meet to experience and discuss the big picture of Digital Transformation and all of the strategies, tactics, and tools they need to realize their goals. Sponsors of DXWorldEXPO | CloudEXPO benefit from unmatched branding, profile building and lead generation opportunities.
DXWorldEXPO LLC announced today that All in Mobile, a mobile app development company from Poland, will exhibit at the 22nd International CloudEXPO | DXWorldEXPO. All In Mobile is a mobile app development company from Poland. Since 2014, they maintain passion for developing mobile applications for enterprises and startups worldwide.
The best way to leverage your CloudEXPO | DXWorldEXPO presence as a sponsor and exhibitor is to plan your news announcements around our events. The press covering CloudEXPO | DXWorldEXPO will have access to these releases and will amplify your news announcements. More than two dozen Cloud companies either set deals at our shows or have announced their mergers and acquisitions at CloudEXPO. Product announcements during our show provide your company with the most reach through our targeted audienc...
@DevOpsSummit at Cloud Expo, taking place November 12-13 in New York City, NY, is co-located with 22nd international CloudEXPO | first international DXWorldEXPO and will feature technical sessions from a rock star conference faculty and the leading industry players in the world.
Everything run by electricity will eventually be connected to the Internet. Get ahead of the Internet of Things revolution. In his session at @ThingsExpo, Akvelon expert and IoT industry leader Sergey Grebnov provided an educational dive into the world of managing your home, workplace and all the devices they contain with the power of machine-based AI and intelligent Bot services for a completely streamlined experience.
DXWorldEXPO | CloudEXPO are the world's most influential, independent events where Cloud Computing was coined and where technology buyers and vendors meet to experience and discuss the big picture of Digital Transformation and all of the strategies, tactics, and tools they need to realize their goals. Sponsors of DXWorldEXPO | CloudEXPO benefit from unmatched branding, profile building and lead generation opportunities.
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
In his keynote at 19th Cloud Expo, Sheng Liang, co-founder and CEO of Rancher Labs, discussed the technological advances and new business opportunities created by the rapid adoption of containers. With the success of Amazon Web Services (AWS) and various open source technologies used to build private clouds, cloud computing has become an essential component of IT strategy. However, users continue to face challenges in implementing clouds, as older technologies evolve and newer ones like Docker c...
JETRO showcased Japan Digital Transformation Pavilion at SYS-CON's 21st International Cloud Expo® at the Santa Clara Convention Center in Santa Clara, CA. The Japan External Trade Organization (JETRO) is a non-profit organization that provides business support services to companies expanding to Japan. With the support of JETRO's dedicated staff, clients can incorporate their business; receive visa, immigration, and HR support; find dedicated office space; identify local government subsidies; get...
Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: Driving Business Strategies with Data Science," is responsible for setting the strategy and defining the Big Data service offerings and capabilities for EMC Global Services Big Data Practice. As the CTO for the Big Data Practice, he is responsible for working with organizations to help them identify where and how to start their big data journeys. He's written several white papers, is an avid blogge...
Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: Driving Business Strategies with Data Science," is responsible for setting the strategy and defining the Big Data service offerings and capabilities for EMC Global Services Big Data Practice. As the CTO for the Big Data Practice, he is responsible for working with organizations to help them identify where and how to start their big data journeys. He's written several white papers, is an avid blogge...