Android foundation summarizes XML data and JSON data

One XML data

1.1 introduction to XML data

XML, or Extensible Markup Language, is very suitable for world wide web transmission. It provides a unified method to describe and exchange structured data independent of applications or suppliers. It is widely used on the Internet.

  • To transfer data rather than display data, you need to customize the label as plain text
  • Case sensitive, correctly nested, attribute values are quoted, spaces are reserved, and there must be a root element

1.2 comparison of three XML parsing methods

1.3 core code

  • ① SAX parsing class: SaxHelper.java
public class SaxHelper extends DefaultHandler {
    private Person person;
    private ArrayList<Person> persons;
    //Currently resolved element label
    private String tagName = null;
    
    /**
     * When reading the document start flag is triggered, some initialization operations are usually completed here
     */
    @Override
    public void startDocument() throws SAXException {
        this.persons = new ArrayList<Person>();
        Log.i("SAX", "Read to document header,Start parsing xml");
    }


    /**
     * Called when a start tag is read. The second parameter is the tag name and the last parameter is the attribute array
     */
    @Override
    public void startElement(String uri, String localName, String qName,
                             Attributes attributes) throws SAXException {
        if (localName.equals("person")) {
            person = new Person();
            person.setId(Integer.parseInt(attributes.getValue("id")));
            Log.i("SAX", "Start processing person element~");
        }
        this.tagName = localName;
    }


    /**
     * After reading the content, the first parameter is the string content, followed by the starting position and length
     */

    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        //Determine whether the current tag is valid
        if (this.tagName != null) {
            String data = new String(ch, start, length);
            //Read the contents of the label
            if (this.tagName.equals("name")) {
                this.person.setName(data);
                Log.i("SAX", "handle name Element content");
            } else if (this.tagName.equals("age")) {
                this.person.setAge(Integer.parseInt(data));
                Log.i("SAX", "handle age Element content");
            }
        }
    }

    /**
     * Triggered at the end of the processing element, where the object is added to the union
     */
    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        if (localName.equals("person")) {
            this.persons.add(person);
            person = null;
            Log.i("SAX", "handle person End of element~");
        }
        this.tagName = null;
    }

    /**
     * Triggered when the end of the document is read,
     */
    @Override
    public void endDocument() throws SAXException {
        super.endDocument();
        Log.i("SAX", "Read to end of document,xml End of parsing");
    }

    //Get the persons collection
    public ArrayList<Person> getPersons() {
        return persons;
    }
}
  • ② Dom parsing class:
public class DomHelper {
    public static ArrayList<Person> queryXML(Context context)
    {
        ArrayList<Person> Persons = new ArrayList<Person>();
        try {
            //① Get an example of a DOM parser factory:
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            //② Get the DOM parser from the DOM factory
            DocumentBuilder dbBuilder = dbFactory.newDocumentBuilder();
            //③ Read the xml file to be parsed into the Dom parser
            Document doc = dbBuilder.parse(context.getAssets().open("person2.xml"));
            System.out.println("To process this document DomImplemention object=" + doc.getImplementation());
            //④ Get the node list of the element named person in the document
            NodeList nList = doc.getElementsByTagName("person");
            //⑤ Traverse the collection, displaying the names of the elements and child elements in the collection
            for(int i = 0;i < nList.getLength();i++)
            {
                //Start with the Person element
                Element personElement = (Element) nList.item(i);
                Person p = new Person();
                p.setId(Integer.valueOf(personElement.getAttribute("id")));

                //Get the Note collection of name and age under person
                NodeList childNoList = personElement.getChildNodes();
                for(int j = 0;j < childNoList.getLength();j++)
                {
                    Node childNode = childNoList.item(j);
                    //Judge whether the sub note type is a note element
                    if(childNode.getNodeType() == Node.ELEMENT_NODE)
                    {
                        Element childElement = (Element) childNode;
                        if("name".equals(childElement.getNodeName()))
                            p.setName(childElement.getFirstChild().getNodeValue());
                        else if("age".equals(childElement.getNodeName()))
                            p.setAge(Integer.valueOf(childElement.getFirstChild().getNodeValue()));
                    }
                }
                Persons.add(p);
            }
        } catch (Exception e) {e.printStackTrace();}
        return Persons;
    }
}
  • ③ Pull parsing class:
public static ArrayList<Person> getPersons(InputStream xml)throws Exception{
    //XmlPullParserFactory pullPaser = XmlPullParserFactory.newInstance();
    ArrayList<Person> persons = null;
    Person person = null;
    // Create an xml parsing factory  
    XmlPullParserFactory factory = XmlPullParserFactory.newInstance();  
    // Get a reference to the xml parsing class  
    XmlPullParser parser = factory.newPullParser();  
    parser.setInput(xml, "UTF-8");  
    // Gets the type of event  
    int eventType = parser.getEventType();  
    while (eventType != XmlPullParser.END_DOCUMENT) {  
        switch (eventType) {  
        case XmlPullParser.START_DOCUMENT:  
            persons = new ArrayList<Person>();  
            break;  
        case XmlPullParser.START_TAG:  
            if ("person".equals(parser.getName())) {  
                person = new Person();  
                // Fetch attribute value  
                int id = Integer.parseInt(parser.getAttributeValue(0));  
                person.setId(id);  
            } else if ("name".equals(parser.getName())) {  
                String name = parser.nextText();// Get the content of this node  
                person.setName(name);  
            } else if ("age".equals(parser.getName())) {  
                int age = Integer.parseInt(parser.nextText());  
                person.setAge(age);  
            }  
            break;  
        case XmlPullParser.END_TAG:  
            if ("person".equals(parser.getName())) {  
                persons.add(person);  
                person = null;  
            }  
            break;  
        }  
        eventType = parser.next();  
    }  
    return persons;  
}  

I. JSON data

1.1 JSON data introduction

  • What's Jason?
    JavaScript object naming, a lightweight data exchange format, is a widely used solution for client-side and server-side interaction like XML! It has the characteristics of good readability and easy to write quickly.
  • Comparison between Json and XML:
    • The data readability of JSON and XML is basically the same;

    • JSON and XML also have rich parsing tools

    • Compared with XML, JSON has a small volume of data

    • The interaction between JSON and JavaScript is more convenient

    • JSON is less descriptive of data than XML

    • JSON is much faster than XML

      Small size, save traffic, but not as intuitive as XML and slightly worse readability!

  • Json's format specification
    json has two data structures
    • One is an unordered jsonObject object in the form of (key/value) pairs,
      An object starts with "{" (left curly bracket) and ends with "}" (right curly bracket). Each "name" is followed by a ":" (colon); "," (comma) is used to separate the 'name / value' pairs.
      For example: {"name": "xiaoluo"}, this is the simplest json object. For this data format, the key value must be of string type, while for value, it can be of string, number, object, array and other data types:

    • A data format is an ordered set of values. This form is called jsonArray, and an array is an ordered set of values.
      An array starts with "[" (left bracket) and ends with "]" (right bracket). Values are separated by "," (comma).
      For example: {[{"key11": "value11", "key12": "value12"}, {"key21": "value21"}, {"key31": "value31"}]}

  • Json parsing class
    • JSONObject: Json object, which can complete the conversion between Json string and Java object
    • JSONArray: Json array, which can complete the conversion between Json string and Java collection or object
    • JSONStringer: JSON text construction class. This class can help create JSON text quickly and conveniently. Each JSONStringer entity can only create one JSON text
    • JSONTokener: Json parsing class
    • JSONException: Json exception

1.2 JSON data parsing

Code example:
JSON data: test.json

{
   "language":[
       {"id":1, "ide":"Eclipse", "name":"Java"},
       {"id":2, "ide":"XCode", "name":"Swift"},
       {"id":3, "ide":"Visual Studio", "name":"C#"}
   ],
   "cat":"it"
}

Data analysis:

try {
            InputStreamReader inputStreamReader = new InputStreamReader(getAssets().open("test.json"), "UTF-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String line;
            StringBuilder stringBuilder = new StringBuilder();
            while((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
            bufferedReader.close();
            inputStreamReader.close();
            JSONObject jsonObject = new JSONObject(stringBuilder.toString());
            JSONArray jsonArray = jsonObject.getJSONArray("language");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject object = jsonArray.getJSONObject(i);
                Log.i("testjson: ", "id=" + object.getInt("id"));
                Log.i("testjson: ", "name=" + object.getString("name"));
                Log.i("testjson: ", "ide=" + object.getString("ide"));
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }

Keywords: Android JSON xml

Added by cwarn23 on Tue, 26 Oct 2021 06:06:38 +0300