Android create JSON string

Nowadays, JSON becomes a useful data-interchanges format that is easy to generate, transmit, and read by any programming language. It is an alternative to XML. You can create a JSON string in Android and use it on Android or send it your web page. You can create a JSON string in PHP and transmit the string to an Android application which parses the string.

In this Android tip, I am going to show you how to create a JSON string in Android. In Android, there are two important classes used to generate a JSON string. They are JSONArray and JSONObject. In a JSONArray instance, you can store different type of data including JSONObject. Below is a JSON string that is created from a JSONArray that has three string items.
["Galaxy Note3","Galaxy S4","Galaxy S4"]

JSONArray list = new JSONArray();    
try {
list2.put(0, "Galaxy Grand");
list2.put(1, "Galaxy S4");
list2.put(2, "Galaxy S3");
} catch (JSONException e1) {
// TODO Auto-generated catch block

Here is another example JSON string. This JSON string created from a JSONArray that has two JSONObject instances. In each JSONObject instance, there are three pairs of name and value. cid, cphone, and cname are names. 1, 855233098, Dara Sok are values.

[{"cid":"1","cphone":"855233098","cname":"Dara Sok"},{"cid":"2","cphone":"855233098","cname":"Chan Thorn"}]

The code to generate this JSON string is shown below.

JSONArray list = new JSONArray();
JSONObject obj1=new JSONObject();
SONObject obj2=new JSONObject();
try {
obj1.put("cid", "1");
obj1.put("cname","Dara Sok");
obj1.put("cphone", "855233098");
obj2.put("cid", "2");
obj2.put("cname","Chan Thorn");
obj2.put("cphone", "855233098");
list.put(0, obj1);
list.put(1, obj2);

} catch (JSONException e) {
// TODO Auto-generated catch block
Log.i("Main", st);

You should note that in JSON, curly braces ({}) hold an object and square brackets ([]) hold an array.


Posted by: Dara | post date: 01-14-2015 | Subject: Android Apps Development

write programming tip

This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.