Q-1 What is parsing? Explain JSON parsing with example.
- Extensible Markup Language (XML) is a set of rules for encoding documents in machine-readable form
- XML is a popular format for sharing data on the internet.
- Websites that frequently update their content, such as news sites or blogs, often provide an XML feed so that external programs can keep abreast of content changes.
- Uploading and parsing XML data is a common task for network-connected apps.
- We will see how to parse XML documents and use their data.
- XmlPullParser, which is an efficient and maintainable way to parse XML on Android. Historically Android has had two implementations of this interface:
- KXmlParser via XmlPullParserFactory.newPullParser()
- ExpatPullParser via Xml.newPullParser()
JSON Parsing
- JSON stands for JavaScript Object Notation
- It is an independent data exchange format and is the best alternative for XML.
- Android provides four different classes to manipulate JSON data.
- These classes are JSONArray, JSONObject, JSONStringer and JSONTokenizer.
- The first step is to identify the fields in the JSON data in which you are interested in. For example. In the JSON given below we interested in getting temperature only.
{ "sys": { "country": "GB", "sunrise": 1381107633, "sunset": 1381149604 }, "weather": [ { "id": 711, "main": "Smoke", "description": "smoke", "icon": "50n" } ], "main": { "temp": 304.15, "pressure": 1009 } }
JSON – Elements
An JSON file consist of many components. Here is the table defining the components of an JSON file and their description –
Array([) – In a JSON file , square bracket ([) represents a JSON array
Objects({) – In a JSON file, curly bracket ({) represents a JSON object
Key – A JSON object contains a key that is just a string. Pairs of key/value make up a JSON object
Value – Each key has a value that could be string, integer or double etc.,
JSON – Parsing
For parsing a JSON object, we will create an object of class JSONObject and specify a string containing JSON data to it. Its syntax is –
String in:
JSONObject reader = new JSONObject(in); The last step is to parse the JSON. A JSON file consist of different object with different key/value pair e.t.c. So JSONObject has a separate function for parsing each of the component of JSON file. Its syntax is given below –
JSONObject sys = reader.getJSONObject("sys"); country = sys.getString("country"); JSONObject main = reader.getJSONObject("main"); temperature = main.getString("temp");
The method getJSONObject returns the JSON object. The method getString returns the string value of the specified key.
Sample JSON Parsing
protected Void doInBackground(Void arg[0]) { HttpHandler sh = new HttpHandler(); // Making a request to url and getting response String url = "http://api.twitteruser.info/contacts/"; String jsonStr = sh.makeServiceCall(url); Log.e(TAG, "Response from url: " + jsonStr); if (jsonStr != null) { try { JSONObject jsonObj = new JSONObject(jsonStr); // Getting JSON Array node JSONArray contacts = jsonObj.getJSONArray("contacts"); // looping through All Contacts for (int i = 0; i < contacts.length(); i++) { JSONObject c = contacts.getJSONObject(i); String id = c.getString("id"); String name = c.getString("name"); String email = c.getString("email"); String address = c.getString("address"); String gender = c.getString("gender"); // Phone node is JSON Object JSONObject phone = c.getJSONObject("phone"); String mobile = phone.getString("mobile"); String home = phone.getString("home"); String office = phone.getString("office"); // tmp hash map for single contact HashMap<String, String> contact = new HashMap<>(); // adding each child node to HashMap key => value contact.put("id", id); contact.put("name", name); contact.put("email", email); contact.put("mobile", mobile); // adding contact to contact list contactList.add(contact); } } catch (final JSONException e) { Log.e(TAG, "Json parsing error: " + e.getMessage()); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), "Json parsing error: " + e.getMessage(), Toast.LENGTH_LONG).show(); } }); }} else { Log.e(TAG, "Couldn't get json from server."); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), "Couldn't get json from server.", Toast.LENGTH_LONG).show(); } }); } return null; }