forked from ServiceStack/ServiceStack.Text
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathJsonObject.cs
More file actions
89 lines (75 loc) · 2.17 KB
/
JsonObject.cs
File metadata and controls
89 lines (75 loc) · 2.17 KB
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
using System;
using System.Collections.Generic;
namespace ServiceStack.Text
{
public static class JsonExtensions
{
public static T JsonTo<T>(this Dictionary<string, string> map, string key)
{
return Get<T>(map, key);
}
public static T Get<T>(this Dictionary<string, string> map, string key)
{
string strVal;
return map.TryGetValue(key, out strVal) ? JsonSerializer.DeserializeFromString<T>(strVal) : default(T);
}
public static string Get(this Dictionary<string, string> map, string key)
{
string strVal;
return map.TryGetValue(key, out strVal) ? strVal : null;
}
public static JsonArrayObjects ArrayObjects(this string json, string propertyName)
{
return Text.JsonArrayObjects.Parse(json);
}
public static List<T> ConvertAll<T>(this JsonArrayObjects jsonArrayObjects, Func<JsonObject, T> converter)
{
var results = new List<T>();
foreach (var jsonObject in jsonArrayObjects)
{
results.Add(converter(jsonObject));
}
return results;
}
public static T ConvertTo<T>(this JsonObject jsonObject, Func<JsonObject, T> converFn)
{
return jsonObject == null
? default(T)
: converFn(jsonObject);
}
public static Dictionary<string, string> ToDictionary(this JsonObject jsonObject)
{
return jsonObject == null
? new Dictionary<string, string>()
: new Dictionary<string, string>(jsonObject);
}
}
public class JsonObject : Dictionary<string, string>
{
public static JsonObject Parse(string json)
{
return JsonSerializer.DeserializeFromString<JsonObject>(json);
}
public JsonArrayObjects ArrayObjects(string propertyName)
{
string strValue;
return this.TryGetValue(propertyName, out strValue)
? JsonArrayObjects.Parse(strValue)
: null;
}
public JsonObject Object(string propertyName)
{
string strValue;
return this.TryGetValue(propertyName, out strValue)
? Parse(strValue)
: null;
}
}
public class JsonArrayObjects : List<JsonObject>
{
public static JsonArrayObjects Parse(string json)
{
return JsonSerializer.DeserializeFromString<JsonArrayObjects>(json);
}
}
}