Let us focus on how to parse JSON results in Android.
We can parse JSON by 2 methods
i) Using JSONObject and JSONTokener classes provided by Android SDK.
ii) Using external libraries. E.g GSON, Jackson etc.
(for more details refer http://json.org)
Let’s consider JSON data of the form:
{
“name”: “myName”,
“message”: ["myMessage1","myMessage2"],
“place”: “myPlace”,
“date”: ”thisDate”
}
“name”: “myName”,
“message”: ["myMessage1","myMessage2"],
“place”: “myPlace”,
“date”: ”thisDate”
}
Parsing JSON data using JSONTokener
public class main extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
/* Inflate TextView from the layout */
TextView tv = (TextView)findViewById(R.id.TextView01);
/* JSON data considered as an example. Generally this data is obtained
from a web service.*/
String json = “{”
+ “ \”name\”: \”myName\”, ”
+ “ \”message\”: [\"myMessage1\",\"myMessage2\"],”
+ “ \”place\”: \”myPlace\”, ”
+ “ \”date\”: \”thisDate\” ”
+ “}”;
/* Create a JSON object and parse the required values */
JSONObject object = (JSONObject) new JSONTokener(json).nextValue();
String name = object.getString(“name”);
String place = object.getString(“place”);
String date = object.getString(“date”);
JSONArray message = object.getJSONArray(“message”);
tv.setText(“Name: “+ name +”\n\n”);
tv.append(“Place: “+ place +”\n\n”);
tv.append(“Date: “+ date +”\n\n”);
for(int i=0;i<message.length();i++)
{
tv.append(“Message: “+ message.getString(i) +”\n\n”);
}
} catch (JSONException e) {e.printStackTrace();}
catch(Exception ex){ex.printStackTrace();}
}
}
No comments:
Post a Comment