Object Model Vs Streaming Model

Object Model Api:
The model creates an object in memory thus enabling easy navigation and creation:

Example of easy navigating: Java

import javax.json.Json;
import javax.json.JsonObject;

Path file = Paths.get("book.json");

InputStream stream = Files.newInputStream(file);

try(JsonReader reader = Json.createReader(stream)){
  JsonArray array= reader.readArray(); 
  for(int i =0 ; i < array.size(); i++){
    array.getJsonObject(i).getInt("id"); 
  } 
}


Example of creating an easy xml object model: Python

 

 

from xml.dom.minidom import getDOMImplementation

impl = getDOMImplementation()

newdoc = impl.createDocument(None, "some_tag", None)
top_element = newdoc.documentElement
text = newdoc.createTextNode('Some textual content.')
top_element.appendChild(text)

Streaming Model Api: is used when large amounts of data exist and PC memory can’t store it’s size on an object.

It is an event based forward parser (process or discard), and doesn’t keep history in memory.

 

Example Java:

import javax.json.Json;
import javax.json.stream.JsonParser; 

JsonParser parser = Json.createParser(new StringReader(jsonData));
while (parser.hasNext()) {
   JsonParser.Event event = parser.next();
   switch(event) {
      case START_ARRAY:
      case END_ARRAY:
      case START_OBJECT:
      case END_OBJECT:
      case VALUE_FALSE:
      case VALUE_NULL:
      case VALUE_TRUE:
         System.out.println(event.toString());
         break;
      case KEY_NAME:
         System.out.print(event.toString() + " " +
                          parser.getString() + " - ");
         break;
      case VALUE_STRING:
      case VALUE_NUMBER:
         System.out.println(event.toString() + " " +
                            parser.getString());
         break;
   }
}

Python Example

from xml.sax.handler import ContentHandler
from xml.sax import make_parser
import sys

class staffmember(ContentHandler):

    def __init__(self):
        self.name = None
        self.inkid = 0

    def startElement(self, name, attrs):
        if name == "name" :
            self.name = ""
        if name == "person":
            self.kids = []
        if name == "kid":
            self.inkid = 1

    def endElement(self,name):
        global kidtable
        if name == "name" :
            self.holdname = self.name
            self.name = None
        if name == "person":
            kidtable[self.holdname] = self.kids
        if name == "kid":
            self.inkid = 0

    def characters(self, chars):
        if self.name != None:
            self.name += chars
        if self.inkid:
            self.kids.append(chars)

staff = staffmember()

kidtable = {}

saxparser = make_parser()
saxparser.setContentHandler(staff)

datasource = open("simpull.xml","r")
saxparser.parse(datasource)

print kidtable