-
Notifications
You must be signed in to change notification settings - Fork 7
/
DynaJSON.cs
48 lines (42 loc) · 1.38 KB
/
DynaJSON.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;
using System.Dynamic;
using Newtonsoft.Json.Linq;
namespace HastyAPI {
public class DynaJSON {
public static dynamic Parse(string text) {
var js = Newtonsoft.Json.JsonConvert.DeserializeObject(text);
return GetValue(js) ?? text;
}
private static dynamic GetObject(JObject jobj) {
var obj = new FriendlyDynamic() as IDictionary<string, object>;
foreach(var pair in jobj) {
obj.Add(pair.Key.Replace('-', '_'), GetValue(pair.Value));
}
return obj;
}
private static object GetValue(object val) {
if(val is JArray) {
return GetList(val as JArray);
} else if(val is JObject) {
return GetObject(val as JObject);
} else if(val is JValue) {
return ((JValue)val).Value;
}
return val; // primitive
}
private static object GetToken(JToken token) {
return token.GetType();
}
private static dynamic GetList(JArray ary) {
var list = new List<object>(ary.Count);
foreach(var e in ary) {
list.Add(GetValue(e));
}
return list;
}
}
}