- JsonWriter writer = new JsonWriter(new OutputStreamWriter(entityStream, "UTF-8"));
- writer.setIndent(" ");
- writer.beginObject();
- convertNodeToJsonAccordingToSchema(writer, t.getData(), t.getSchema());
- writer.endObject();
- }
-
- private void convertNodeToJsonAccordingToSchema(JsonWriter writer, Node<?> node, DataSchemaNode dataSchemaNode) throws IOException {
- if (node instanceof CompositeNode) {
- if (!(dataSchemaNode instanceof DataNodeContainer)) {
- throw new IllegalStateException("CompositeNode should be represented as DataNodeContainer");
- }
- if (dataSchemaNode instanceof ContainerSchemaNode) {
- writer.name(node.getNodeType().getLocalName());
- writer.beginObject();
- String listName = "";
- for (Node<?> n : ((CompositeNode) node).getChildren()) {
- DataSchemaNode foundDataSchemaNode = findSchemaForNode(n, ((DataNodeContainer) dataSchemaNode).getChildNodes());
- if (foundDataSchemaNode instanceof ListSchemaNode) {
- if (listName.equals(n.getNodeType().getLocalName())) {
- continue;
- }
- listName = n.getNodeType().getLocalName();
- }
- convertNodeToJsonAccordingToSchema(writer, n, foundDataSchemaNode);
- }
- writer.endObject();
- } else if (dataSchemaNode instanceof ListSchemaNode) {
- writer.name(node.getNodeType().getLocalName());
- writer.beginArray();
- List<Node<?>> nodeSiblings = node.getParent().getChildren();
- for (Node<?> nodeSibling : nodeSiblings) {
- if (nodeSibling.getNodeType().getLocalName().equals(node.getNodeType().getLocalName())) {
- DataSchemaNode schemaForNodeSibling = findSchemaForNode(nodeSibling,
- ((DataNodeContainer) dataSchemaNode.getParent()).getChildNodes());
- writer.beginObject();
- for (Node<?> child : ((CompositeNode) nodeSibling).getChildren()) {
- DataSchemaNode schemaForChild = findSchemaForNode(child,
- ((DataNodeContainer) schemaForNodeSibling).getChildNodes());
- convertNodeToJsonAccordingToSchema(writer, child, schemaForChild);
- }
- writer.endObject();
- }
- }
- writer.endArray();
- }
- } else if (node instanceof SimpleNode<?>) {
- if (!(dataSchemaNode instanceof LeafSchemaNode)) {
- throw new IllegalStateException("SimpleNode should should be represented as LeafSchemaNode");
- }
- writeLeaf(writer, (LeafSchemaNode) dataSchemaNode, (SimpleNode<?>) node);