JSON and XML Parsing in Android

1. JSON

First we talk about basic knowledge of JSON.
JSON stands for JavaScript Object Notation,it's a lightweight data-interchange format. It is easy for user to read and write.
whenever we want to use JSON parsing for should know about JSON syntax like 

 name/value pairs,separated by commas,Curly braces for hold array
there are five type values use in JSON Array,Boolean,Number,Object,String
1.Json Arrray:-JSONArray to parse JSON which is starts brackets ([ ]) of Array.for  example [{"item1":"value1"},{"item2": "value2"} ]
2.Josn Object:-it's begins with curly braces ({ }) and use to contain key/value pairs. for example {"item1":"value1"},{"item2": "value2"}
3.if we talk about json in deep the json can be nested inside one another for example
{"jsonObject": 0, "jsonArray":  [{"item1":"value1"},{"item2": "value2"}] }

Let,s we talk about JSON Parsing with GET and POST method in Android.

1.Create HTTP Connection for getting response from server with GET Method 

public static String findJSONFromUrl(String url) {
String result = "";
try {
         URL urls = new URL(url);
         HttpURLConnection conn = (HttpURLConnection) urls.openConnection();
         conn.setReadTimeout(150000);/* milliseconds */
         conn.setConnectTimeout(15000); /* milliseconds */
         conn.setRequestMethod("GET");
         conn.connect();
         BufferedReader reader = new BufferedReader(new InputStreamReader(
         conn.getInputStream(), "iso-8859-1"), 8);
         StringBuilder sb = new StringBuilder();
         String line = null;

    while ((line = reader.readLine()) != null)
       {
               sb.append(line + "\n");
        }
              result = sb.toString();
catch (Exception e) {
 // System.out.println("exception in jsonparser class ........");
      e.printStackTrace();
return null;
}
return result;
 } // method ends 




2.Create HTTP Connection for getting response from server with POST Method 


//  create ArrayLiat for your params
ArrayList param= new ArrayList<>();
param.add("key1"="Your Value1");
param.add("&key2"="Your Value2");
param.add("&key3"="Your Value3") ;                                                                                   

//This is a methid for post data on server and get responce     
public static String postData(String url, ArrayList<String> params) {       
// TODO Auto-generated method stub
String response = "";
  try {
          URL urls = new URL(url);
          HttpURLConnection con = (HttpURLConnection) urls.openConnection();
          con.setConnectTimeout(15000);
          con.setReadTimeout(15000);
          con.setDoInput(true);
          con.setDoOutput(true); // true indicates POST request
          con.setRequestMethod("POST");
          con.connect();
    if (con != null) {
        // TODO: write or sends POST data in form of byte
    try {
            StringBuffer requestParams = new StringBuffer();
            String value = "";
           if (params != null && params.size() > 0) {
           // creates the params string, encode them using URLEncoder
              Iterator<String> paramIterator = params.iterator();
              while (paramIterator.hasNext()) {
             value = paramIterator.next();
             // Convertin arraylist value inform of bytes
    try {
            DataOutputStream wr = new DataOutputStream(
            con.getOutputStream());
            wr.writeBytes(value);
            wr.flush();
    catch (Exception e) {
         e.printStackTrace();
          }
    }

if (con.getResponseCode() == HttpURLConnection.HTTP_OK && con != null) {
         BufferedReader bufferedReader = new BufferedReader(
         new InputStreamReader(con.getInputStream()));
         StringBuilder stringBuilder = new StringBuilder();
         String data;
      while ((data = bufferedReader.readLine()) != null) {
          stringBuilder.append(data + "\n");

            }
            response = stringBuilder.toString();
         }
     }
         con.disconnect();
     }
   catch (Exception e) {
       e.printStackTrace();
  }
 return response;
}// method ends 

4.After getting responce from server get data from JSONArray
suppose responce :-
{"jsonObject": 0,"jsonArray":  [{"item1":"value1"},{"item2": "value2"},{"item3": "value3"}] }

JSONArray jsonArray = new JSONArray("jsonArray");
   if (jsonArray != null) {
        for (int i = 0; i < jsonArray.length(); i++) {
      JSONObject     jsonObject = jsonArray.getJSONObject(i);
      String  value1 = jsonObject.getString("item1");
      String  value2 = jsonObject.getString("item2");
      String  value3 = jsonObject.getString("item3");
}
}

5.After getting response from server get data from JSONObject 
 JSONObject     jsonObject = new JSONObject("Object Name");
      String  value1 = jsonObject.getString("your key1");
      String  value2 = jsonObject.getString("your key2");
      String  value3 = jsonObject.getString("your key3");


2.XML
First we'll Know about 'what is XML?'
XML is a EXtensible Markup Language and it was design to describe data;
XML tags are not predefined. You must define your own tags; 

XML Parsing
with the help of XmlPullParser to parse XML in Android.there are following methods to parse XML
Method startDocument() :- Method called at the start of an XML document.
Method endDocument()  :-  Method called at  end of an XML document.
Method startElement() :-Method called at the start of a document element.
Method endElement()  :- Method called at  end of a document element.  

characters() – Method called with the text contents in between the start and end tags of an XML document element.

Here an Example of XML parsing
try {
    XmlPullParserFactory xmlfact = XmlPullParserFactory.newInstance();  
    xmlfact.setNamespaceAware(true);
    XmlPullParser parser = xmlfact.newPullParser();
    StringReader sr = new StringReader(result);
    parser.setInput(sr);
      int eventtype = parser.getEventType(); 
      String tag1="";
      String tag2="";
  while(eventtype!=XmlPullParser.END_DOCUMENT)
  {
     if(eventtype==XmlPullParser.START_TAG && parser.getName().equals("item"))
    {
       eventtype = parser.next();
     while(true)
      {
         if(eventtype==XmlPullParser.END_TAG && parser.getName().equals("item"))
          break;
          if(eventtype==XmlPullParser.START_TAG &&                                                                parser.getName().equals("title"))
          {
             eventtype = parser.next();
              tag1 = parser.getText();
           }
         if(eventtype==XmlPullParser.START_TAG &&                                                                   parser.getName().equals("link"))
          {
        eventtype = parser.next();
        tag2 = parser.getText();
      }
     eventtype = parser.next();
    }
         Score sc = new Score(tag1, tag2);
         list.add(sc);
         adp.notifyDataSetChanged();
    }
        eventtype = parser.next();
  }
 } catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}