První nástřel – trochu už to funguje, převádí JSON na XML.
1 package cz.frantovo.alt2xml;
3 import java.io.IOException;
4 import java.util.Stack;
5 import org.json.simple.parser.ParseException;
6 import org.xml.sax.ContentHandler;
7 import org.xml.sax.SAXException;
13 public class JsonSimpleContentHandler implements org.json.simple.parser.ContentHandler {
15 /** Sem vypisujeme XML události */
16 private ContentHandler saxVýstup;
17 /** Musíme si pamatovat polohu v XML stromu, abychom věděli, kterou značku kdy uzavřít */
18 private Stack<String> poloha = new Stack<>();
20 public JsonSimpleContentHandler(ContentHandler saxVýstup) {
21 this.saxVýstup = saxVýstup;
25 public void startJSON() throws ParseException, IOException {
27 saxVýstup.startDocument();
28 saxVýstup.startElement(null, null, "json", null);
29 } catch (SAXException e) {
30 throw new IOException(e);
35 public void endJSON() throws ParseException, IOException {
37 saxVýstup.endElement(null, null, "json");
38 saxVýstup.endDocument();
39 } catch (SAXException e) {
40 throw new IOException(e);
45 public boolean startObject() throws ParseException, IOException {
46 // System.err.println("startObject");
51 public boolean endObject() throws ParseException, IOException {
52 // System.err.println("endObject");
57 public boolean startObjectEntry(String key) throws ParseException, IOException {
59 saxVýstup.startElement(null, null, key, null);
61 } catch (SAXException e) {
62 throw new IOException(e);
64 // System.err.println("startObjectEntry: " + key);
69 public boolean endObjectEntry() throws ParseException, IOException {
71 String značka = poloha.pop();
72 saxVýstup.endElement(null, null, značka);
73 } catch (SAXException e) {
74 throw new IOException(e);
76 // System.err.println("endObjectEntry");
81 public boolean startArray() throws ParseException, IOException {
82 // System.err.println("startArray");
87 public boolean endArray() throws ParseException, IOException {
88 // System.err.println("endArray");
93 public boolean primitive(Object value) throws ParseException, IOException {
95 String hodnota = String.valueOf(value);
96 saxVýstup.characters(hodnota.toCharArray(), 0, hodnota.length());
97 } catch (SAXException e) {
98 throw new IOException(e);
100 // System.err.println("primitive: " + value);