Java ME (J2ME) JSON Implementation Tutorial/Sample

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

31 comments

  1. 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

  2. Nice! Do you have sample for collection that wraps this object? Thta is, convertes JSON string of objects back an forth. Thanks, Ona.

  3. 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

  4. 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

  5. @Sajid:
    Do you mean sending from J2ME application?
    You can use HTTPConnection and stream the json request data with ‘openOutputStream()’ & set using POST Method.

  6. 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

  7. 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

  8. 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.

  9. @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.

  10. kalo cara parsing yg array gimana? :D

    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.

  11. i am getting this error please help to solve this Uncaught exception: java.lang.Error: ClassFormatError: 154

    Regards
    chandrasekhar

  12. 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.

  13. I got this when i used your code in MIDlet : Uncaught exception java/lang/NoClassDefFoundError: org/json/me/JSONException.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

WP-SpamFree by Pole Position Marketing