Your experience on this site will be improved by allowing cookies
JSON stands for the Javascript Object Notation. It is a programming language, minimal, textual, and a subset of JavaScript and an alternative to XML. We can parse the JSON object and array in Android.
Advantages of JSON over XML:
Advantages of XML over JSON:
Similar to a map, the JSON object also contains key/value pairs, separated by a comma, where keys are strings and the values are the JSON types. The JSON object is represented by the { (curly brace).
Example:
{ "student": { "name": "Rohan", "id": 100, "class": 6 } } |
The JSON array is represented by the [ (square bracket).
Example 1:
["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] |
Example 2:
{ "Student" : [ {"id":"1","name":"Rohan","marks":"80"}, {"id":"2","name":"Rohit","marks":"90"} ] } |
In the below example, we will parse the JSONArray containing the JSON Objects using the JSONArray class.
activity_main.xml
In the activity_main.xml file, we will drag a Textview from the palette.
List_row.xml:
Activity class:
In the MainActivity.java file, we will write the code to parse the XML using the JSON parser.
package com.example.radioapp; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); String jsonStr = getListData(); try{ ArrayList> userList = new ArrayList<>(); ListView lv = (ListView) findViewById(R.id.user_list); JSONObject jObj = new JSONObject(jsonStr); JSONArray jsonArry = jObj.getJSONArray("users"); for(int i=0;i user = new HashMap<>(); JSONObject obj = jsonArry.getJSONObject(i); user.put("name",obj.getString("name")); user.put("designation",obj.getString("designation")); user.put("location",obj.getString("location")); userList.add(user); } ListAdapter adapter = new SimpleAdapter(MainActivity.this, userList, R.layout.list_row,new String[]{"name","designation","location"}, new int[]{R.id.name, R.id.designation, R.id.location}); lv.setAdapter(adapter); } catch (JSONException ex){ Log.e("JsonParser Example","unexpected JSON exception", ex); } } private String getListData() { String jsonStr = "{ \"users\" :[" + "{\"name\":\"A\",\"designation\":\"Leader\",\"location\":\"City1\"}" + ",{\"name\":\"B\",\"designation\":\"Secretary\",\"location\":\"City2\"}" + ",{\"name\":\"C\",\"designation\":\"Accountant\",\"location\":\"City3\"}] }"; return jsonStr; } } |
0 comments