Examples of basic methods for Android App to read XML and JSON format data

  • 2021-06-28 13:59:27
  • OfStack

XML
If you have data in this XML format:


<?xml version="1.0" encoding="utf-8"?> 
<resources> 
<customer name="luopeng" age="21" gender="1"   emial="dylankeepmoving@163.com"/> 
<customer name="dylan" age="22" gender="2" emial="710097663@qq.com"/> 
<customer name="android" age="6" gender="2" emial="android@gmail.com"/> 
</resources>

Let's write a class to read that displays the contents of a resource file (an XML) on EditView after clicking the button. XMLResourceParser is used in this example


public class TestXmlResourceParserActivity extends Activity { 
private EditText et; 
private Button myButton; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
  super.onCreate(savedInstanceState); 
  setContentView(R.layout.main); 

  //  A variable used in an internal class must be final Modified  
  myButton = (Button) this.findViewById(R.id.btn01); 
  et = (EditText) this.findViewById(R.id.edittext01); 
  myButton.setOnClickListener(new OnClickListener() { 
    StringBuilder sb = new StringBuilder(""); 
    Resources res = getResources(); 
    XmlResourceParser xrp = res.getXml(R.xml.test); 

    @Override 
    public void onClick(View v) { 
      int counter = 0; 
      try { 
        //  Determine if the end of the file is reached  
        while (xrp.getEventType() != XmlResourceParser.END_DOCUMENT) { 
          // Start with the start tag of the file's contents, note that the start tag here is test.xml Inside the file <resources> Label No. 1 Labels  
          if (xrp.getEventType() == XmlResourceParser.START_TAG) { 
            String tagname = xrp.getName(); 
            if (tagname.endsWith("customer")) { 
              counter++; 
              sb.append(" This is the first " + counter + " Customer "+"\n"); 
              sb.append(" Full name: "+xrp.getAttributeValue(0)+"\n"); 
              sb.append(" Age: "+xrp.getAttributeValue(1)+"\n"); 
              sb.append(" Gender: "+xrp.getAttributeValue(2)+"\n"); 
              sb.append(" Mailbox: "+xrp.getAttributeValue(3)+"\n\n"); 
            } 
          } 
          xrp.next(); 
        } 
        et.setText(sb.toString()); 
      } catch (XmlPullParserException e) { 
      } catch (IOException e) { 
        e.printStackTrace(); 
      } 
    } 
  }); 
}

JSON
Create JSON data


try {
    // First create the 1 Single key-value pairs 
    JSONObject root = new JSONObject();
    root.put("cat", "it");
    // another 1 The values of the key-value pairs are 1 Arrays, arrays with 3 individual JSON Object, so do it separately 3 individual JSONObject Object holds key-value pairs 
    JSONObject lan1 = new JSONObject();
    lan1.put("id", "1");
    lan1.put("ide", "Eclipse");
    lan1.put("name","Java");
    JSONObject lan2 = new JSONObject();
    lan2.put("id", "2");
    lan2.put("ide", "XCode");
    lan2.put("name","Swift");
    JSONObject lan3 = new JSONObject();
    lan3.put("id", "2");
    lan3.put("ide", "Visual Studio");
    lan3.put("name","C#");
    // Now I'm putting this in 3 Save objects in 1 Arrays 
    JSONArray array = new JSONArray();
    array.put(lan1);
    array.put(lan2);
    array.put(lan3);
    // Then use the array as the key "languages" The value of the 1 Objects 
    root.put("languages", array);
    // In this example, only output the content 
    System.out.println(root.toString());

  } catch (JSONException e) {
    e.printStackTrace();
  }

Read JSON data
assets/test.json


{
  "languages":[
    {"id":1,"ide":"Eclipse","name":"Java"},
    {"id":2,"ide":"XCode","name":"Swift"},
    {"id":3,"ide":"Visual Studio","name":"C#"},
  ],
  "cat","it"
}
try {
    InputStream is = getResources().getAssets().open("test.json");
    InputStreamReader isr = new InputStreamReader(is, "UTF-8");
    BufferedReader br = new BufferedReader(isr);
    // Read all the data in the text 1 individual StringBuilder Among 
    String line;
    StringBuilder builder = new StringBuilder();
    while((line=br.readLine()) != null ){
      builder.append(line);
    }
    br.close();
    isr.close();

    JSONObject root = new JSONObject(builder.toString());
    // From the key, get the value corresponding to the key, since the value is String Type, so use getString
    System.out.println("cat="+root.getString("cat"));
    // Gets an array of keys based on the key, since the value is 1 Arrays, so use getJSONArray
    JSONArray array = root.getJSONArray("languages");
    // Since the array is to be traversed, create 1 individual for loop 
    for(int i=0; i < array. length(); i++){
      // Because every 1 Elements in arrays, also 1 New JSON object 
      JSONObject lan = array.getJSONObject(i);
      System.out.println("-------------------");
      System.out.println("id="+lan.getInt("id"));
      System.out.println("ide="+lan.getString("name"));
      System.out.println("name="+lan.getString("name"));
      Log.i("tag","-------");
    }

  } catch (IOException e) {
    e.printStackTrace();
  } catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }



Related articles: