public static string ToJson(DataNode node) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append('{'); DataNodeJson.ToJson(node, stringBuilder, false); stringBuilder.Append('}'); return(stringBuilder.ToString()); }
public static void ToJsonFile(DataNode node, string fileName) { string value = DataNodeJson.ToJson(node); using (StreamWriter streamWriter = new StreamWriter(fileName)) { streamWriter.Write(value); streamWriter.Close(); } }
public static void ToJson(DataNode node, StringBuilder sb, bool listItem = false) { string arg = "nullName"; if (!string.IsNullOrEmpty(node.Name)) { arg = node.Name; } if (string.IsNullOrEmpty(node.Content)) { if (node.Nodes == null || node.Nodes.Count == 0) { if (listItem) { if (node.IsList) { sb.Append("[]"); } else { sb.Append("\"\""); } } else if (node.IsList) { sb.AppendFormat("\"{0}\":[]", arg); } else { sb.AppendFormat("\"{0}\":\"\"", arg); } } else { if (!listItem) { sb.AppendFormat("\"{0}\":", arg); } if (node.IsList) { sb.Append('['); } else { sb.Append('{'); } for (int i = 0; i < node.Nodes.Count; i++) { DataNode node2 = node.Nodes[i]; DataNodeJson.ToJson(node2, sb, node.IsList); if (i != node.Nodes.Count - 1) { sb.Append(','); } } if (node.IsList) { sb.Append("]"); } else { sb.Append('}'); } } } else { if (node.Nodes != null && node.Nodes.Count > 0) { throw new Exception("Node can't contain content and subnodes"); } if (listItem) { sb.AppendFormat("\"{0}\"", node.Content.Replace("\"", "\\\"")); } else { sb.AppendFormat("\"{0}\":\"{1}\"", arg, node.Content.Replace("\"", "\\\"")); } } }