forked from AlloyTeam/Rosin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJsonObjectTree.cs
102 lines (91 loc) · 2.98 KB
/
JsonObjectTree.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using System.Collections;
namespace EPocalipse.Json.Viewer
{
public enum JsonType { Object, Array, Value };
class JsonParseError : ApplicationException
{
public JsonParseError() : base() { }
public JsonParseError(string message) : base(message) { }
protected JsonParseError(SerializationInfo info, StreamingContext context) : base(info, context) { }
public JsonParseError(string message, Exception innerException) : base(message, innerException) { }
}
public class JsonObjectTree
{
private JsonObject _root;
public static JsonObjectTree Parse(string json)
{
//Parse the JSON string
object jsonObject;
try
{
jsonObject = JavaScriptConvert.DeserializeObject(json);
}
catch (Exception e)
{
throw new JsonParseError(e.Message, e);
}
//Parse completed, build the tree
return new JsonObjectTree(jsonObject);
}
public JsonObjectTree(object rootObject)
{
_root = ConvertToObject("JSON", rootObject);
}
private JsonObject ConvertToObject(string id, object jsonObject)
{
JsonObject obj = CreateJsonObject(jsonObject);
obj.Id = id;
AddChildren(jsonObject, obj);
return obj;
}
private void AddChildren(object jsonObject, JsonObject obj)
{
JavaScriptObject javaScriptObject = jsonObject as JavaScriptObject;
if (javaScriptObject != null)
{
foreach (KeyValuePair<string, object> pair in javaScriptObject)
{
obj.Fields.Add(ConvertToObject(pair.Key, pair.Value));
}
}
else
{
JavaScriptArray javaScriptArray = jsonObject as JavaScriptArray;
if (javaScriptArray != null)
{
for (int i = 0; i < javaScriptArray.Count; i++)
{
obj.Fields.Add(ConvertToObject("[" + i.ToString() + "]", javaScriptArray[i]));
}
}
}
}
private JsonObject CreateJsonObject(object jsonObject)
{
JsonObject obj = new JsonObject();
if (jsonObject is JavaScriptArray)
obj.JsonType = JsonType.Array;
else if (jsonObject is JavaScriptObject)
obj.JsonType = JsonType.Object;
else
{
obj.JsonType = JsonType.Value;
obj.Value = jsonObject;
}
return obj;
}
public JsonObject Root
{
get
{
return _root;
}
}
}
}