Friday, 27 July 2018

json & xml

1. json concept
  • number, string, object, array, boolean, null
  • if start with [, it is a json array
  • if start with {, it is a json object
  • JSON.stringify(obj) convert json object to string
  • JSON.parse(string) convert json string to object
  • json is not extensible

2. json object
myObj = { "name":"John", "age":30, "car":null };

myObj = {                          //nested json object
    "name":"John",
    "cars": {
        "car3":"Fiat"
    }
 }


3. json array (of object)
myObj = {
    "name":"John",
    "cars": [
        { "name":"Ford"},
        { "name":"BMW"},
        { "name":"Fiat"}
    ]
 }


4. java json library (objectmapper)
  • jackson (default for resttemplate, restassured etc)
  • jayway jsonpath

5. xml concept
  • prolog, tag, attribute and element
  • DOM tree, root, parent, child, sibling
  • attribute value must be quoted
  • < less than becomes &lt;
  • online xpath editor @http://xmlgrid.net/xpath.html
  • xml is extensible
  • javascript xml parser
      <?xml version="1.0" encoding="UTF-8"?>       //prolog
      <book category="children">                               //book is tag, category is attribute
          <title>harry Potter</title>                               //element
          <year>2005</year>
      </book>

      parser = new DOMParser();
      xmlDoc = parser.parseFromString(text,"text/xml");


6. xml namespace
<root>

<h:table xmlns:h="http://www.w3.org/TR/html4/">
  <h:tr>
    <h:td>Apples</h:td>
    <h:td>Bananas</h:td>
  </h:tr>
</h:table>

<f:table xmlns:f="https://www.w3schools.com/furniture">
  <f:name>African Coffee Table</f:name>
  <f:width>80</f:width>
  <f:length>120</f:length>
</f:table>

</root>

<table xmlns="http://www.w3.org/TR/html4/">          //default namespace
  <tr>
    <td>Apples</td>
    <td>Bananas</td>
  </tr>
</table>


7. xpath
  • /                         //select from root
  • //                        //from current node, wherever they are
  • .                         //current node
  • ..                        //parent
  • @                      //select attribute

8. java xml library
  • DOM api (tree model, in memory)
  • SAX api (stream based, event driven, push-parsing model)
  • Stax api (stream based, event driven, pull-parsing model)
  • JAXB api (schema based)

9. jaxb
  • marshall: convert java object to xml
  • unmarshall: convert xml to java object
  • jaxb validation: verify that xml or java object tree meet all constraint in xml schema
  • convert schema to jaxb class in eclipse (right click)
  • convert schema to jaxb class online ()

10. xml schema
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

<xs:element name="note">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="to" type="xs:string"/>
    </xs:sequence>
  </xs:complexType>
</xs:element>

</xs:schema>