Java ME (J2ME) JSON Implementation Tutorial/Sample
by jimmy on Mar.03, 2010, under English, Java, Programming
JSON is one of the most popular format used for communicating between (Java ME) J2ME client and App Server. Strangely it’s hard to find JSON implementation sample in J2ME. So I decide to write a sample.
– Next Tutorial : Java ME (J2ME) JSON Implementation For Array Object –
The JSON library I used is from json.org : http://www.json.org/java/org.json.me.zip
(link reported not valid anymore, try the one I’ve uploaded : http://www.megaupload.com/?d=QDW9N225)
Extract it to your source code folder.
For example we have this User Class:
public class User{ private int id; private String name; private String description; }
To implement JSON to this class I usually create an Interface JSONAble:
public interface JSONAble { String toJSON(); void fromJSON(String jsonString); }
To make the User class is JSON compatible
let’s add the JSONAble interface & implement it:
public class User implements JSONAble{ private int id; private String name; private String description; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String toString() { return getId()+"-"+getName()+"-"+getDescription(); } public void fromJSON(String jsonString) { try { JSONObject json = new JSONObject(jsonString); setId(json.getInt("id")); setName(json.getString("name")); setDescription(json.getString("description")); } catch (JSONException ex) { ex.printStackTrace(); } } public String toJSON() { JSONObject inner = new JSONObject(); try { inner.put("id", getId()); inner.put("name", getName()); inner.put("description", getDescription()); } catch (JSONException ex) { ex.printStackTrace(); } return inner.toString(); } }
To test it let’s create a MIDlet that have these startApp() implementation:
protected void startApp() throws MIDletStateChangeException { //Converting Object to JSON User user = new User(); user.setId(10); user.setName("jimmy"); user.setDescription("testing json in j2me"); System.out.println("Convert to JSON : "+user.toJSON()); //Converting JSON to Object String sample = "{\"id\":99,\"name\":\"tester\",\"description\":\"This is JSON Data\"}"; User user2 = new User(); user2.fromJSON(sample); System.out.println("Convert from JSON : "+user2); }
As you can see the output results:
Convert to JSON : {"name":"jimmy","description":"testing json in j2me","id":10}
Convert from JSON : 99-tester-This is JSON Data
The toJSON() function is the implementation how the object converted to JSON format. In J2ME we still implement it manually since we don’t have Java reflection which can enable automatically scan the variables.
What the JSON library help is building the JSON data. We just need to put the variables.
On the fromJSON() function what it does is getting out the data from JSON format and set it to class variables.
Next I will cover about converting more complex class structure.
Or create a fromJSON () & toJSON() generator (:?). Let see..
Thanks for reading this, although this is the basic hope it’ll help
– Next Tutorial : Java ME (J2ME) JSON Implementation For Array Object –
Related posts:
April 24th, 2010 on 9:09 pm
Wie immer… lesenswerter Post. Sorry dass ich mich nie beteilige, auch wenn ich dauernd hier lese.
May 2nd, 2010 on 2:06 pm
Danke
Thank you for reading my articles..
June 12th, 2010 on 2:17 pm
Well written and clear. Thank you.
July 10th, 2010 on 11:12 pm
Hi
I downloaded the file on ubuntu but was not able to extract it. Apparently the file is not created properly?
Can anyone else verify this?
Thanks
nii amon
July 15th, 2010 on 11:45 pm
@nii amon: which file do you download?
You’ll need IDE such as Eclipse Pulsar/Netbeans to try the code
July 28th, 2010 on 12:32 pm
I am using JSON in PHP to interact with server. After reading this article, I can understand JSON implementation bit better than before. Thank you.
September 8th, 2010 on 5:01 pm
Nice! Do you have sample for collection that wraps this object? Thta is, convertes JSON string of objects back an forth. Thanks, Ona.
September 11th, 2010 on 4:19 pm
hi, http://www.json.org/java/org.json.me.zip is no longer available. Does anyone know where to find the package?
Thanks!
September 11th, 2010 on 4:33 pm
hm.. not sure why they take it out (or maybe change the link title).
I’ve upload the one I download before : http://www.megaupload.com/?d=QDW9N225
September 11th, 2010 on 4:41 pm
@Ona:
Not sure what you mean by collections, since the implementation in JavaME is not using reflection we must create custom one depends on the class.
January 22nd, 2011 on 7:55 pm
In this example if the server was returning a list of Users in Json format. How would you pass the Json string with multiple Users to create a list of User objects?
Thanks
March 8th, 2011 on 6:23 pm
Hey hi this is good example for understanding.
Thanks for this.
Can you help me regarding how to send json format data to server.
Thanks
March 25th, 2011 on 3:45 pm
@Sajid:
Do you mean sending from J2ME application?
You can use HTTPConnection and stream the json request data with ‘openOutputStream()’ & set using POST Method.
March 26th, 2011 on 1:25 am
thanks alot for your help , but i need to ask a stupid question , how can i add this library for my j2me app. while using netbeans… i tried properies –>libraries–> add folder and it did not work
March 26th, 2011 on 1:37 am
Sorry again , it finally worked , just a netbeans error, thanks jimmy,
March 26th, 2011 on 5:02 pm
Dear All,
can someone tell will it really make a difference to send and receive JSON msgs instead of using normal string msgs across the network ????????????
If yes then please tell me why and how, because what i can see is that i am parsing the data from and to Strings and in the end i will send the data as bytes so what i can see that JSON is just standard …… please correct if i am wrong
March 27th, 2011 on 1:28 pm
Hi THarwat,
No it will not make a difference. I use JSON to respond to requests from the mobile devices. On the mobile device, I use the fromJson method to transform the JSON string into the domain object on the mobile device and then I can continue as normal.
April 4th, 2011 on 11:38 am
Thanhs jimmy. Good tut!
April 4th, 2011 on 4:56 pm
@Tharwat:
JSON is only a standard format.
Example you have this class People with attributes:
- name
- age
You can create your own ’standard’ to translate this object to a String/array of byte so it can be transfered to server, or using JSON/other popular standard (xml/rpc, xml/soap, etc).
I will choose the popular standard that meet my requirement and if it’s for mobile of course choosing the simplest one.
Using our own standard will be harder to be understood by for other developer.
April 19th, 2011 on 11:10 pm
Hi …
How to use this for lists and objects …
July 5th, 2011 on 12:12 pm
implementing json with jquery in web application made web programming easier,.. pa kabar jim?
July 20th, 2011 on 6:52 pm
@Dedi : great
gimana bandung
August 17th, 2011 on 3:20 am
Nice – thanks for the write up !
August 25th, 2011 on 1:27 am
new version of JSON ME is available at
https://github.com/upictec/org.json.me/
September 9th, 2011 on 4:08 pm
kalo cara parsing yg array gimana?
parsing string like this :
{\”api_status\”: \”OK\”,\”threads\”: [{\"tid\": \"2\",\"title\": \"First Title\" }, { \"tid\": \"4\", \"title\": \"this is 2nd Title\"}]}
it gives me an error :
org.json.me.JSONException: JSONObject[\"tid\"] not found.
September 13th, 2011 on 11:49 pm
@abah:
Please check this article : http://jimmod.com/blog/2011/09/java-me-j2me-json-implementation-for-array-object/
September 20th, 2011 on 8:46 pm
i am getting this error please help to solve this Uncaught exception: java.lang.Error: ClassFormatError: 154
Regards
chandrasekhar
September 21st, 2011 on 12:56 am
@chandra:
The JSON library works with cldc 1.1, maybe you used cldc 1.0
September 26th, 2011 on 6:29 pm
@chandra:
Can you write more detail stack trace.
I’m not sure.
Is there any error in the Eclipse?
Make sure you include the JSon library in build.
January 18th, 2012 on 2:34 am
Once again, you have managed to captivate my mind with another great post. I find it all immensely exciting. Please keep up with more of the great posts I look forward to your next one.