forked from Bunny83/SimpleJSON
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SImpleJSONExtensions.cs
92 lines (79 loc) · 2.67 KB
/
SImpleJSONExtensions.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
using System;
using System.Reflection;
using SimpleJSON;
namespace artics.extensions.SimpleJSON
{
public class ParsableValue : Attribute
{
public string Name;
public ParsableValue() { }
public ParsableValue(string name)
{
Name = name;
}
}
public static class SimpleJSONExtensions
{
public static void ParseData(JSONClass param, object instance)
{
Type thisType = instance.GetType();
FieldInfo[] fields = thisType.GetFields();
foreach (var info in fields)
{
ParsableValue attribute = info.GetCustomAttribute<ParsableValue>(true);
if (attribute == null)
continue;
string name = attribute.Name != null && attribute.Name != string.Empty ? attribute.Name : info.Name;
if (param.containsKey(name))
{
object value = param[name].GetValueByType(info.FieldType);
info.SetValue(instance, value);
}
}
}
public static object GetValueByType(this JSONNode param, Type NeedType)
{
if (NeedType == typeof(int))
return param.AsInt;
else
if (NeedType == typeof(float))
return param.AsFloat;
else
if (NeedType == typeof(double))
return param.AsDouble;
else
if (NeedType == typeof(long))
return param.AsLong;
else
if (NeedType == typeof(bool))
return param.AsBool;
else
if (NeedType == typeof(string))
return param.Value;
throw (new Exception("Type " + NeedType.Name + " is not supported"));
}
public static T GetValueByType<T>(this JSONNode param)
{
Type NeedType = typeof(T);
if (NeedType == typeof(int))
return (T)(object)param.AsInt;
else
if (NeedType == typeof(float))
return (T)(object)param.AsFloat;
else
if (NeedType == typeof(double))
return (T)(object)param.AsDouble;
else
if (NeedType == typeof(long))
return (T)(object)param.AsLong;
else
if (NeedType == typeof(bool))
return (T)(object)param.AsBool;
else
if (NeedType == typeof(string))
return (T)(object)param.Value;
throw (new Exception("Type " + NeedType.Name + " is not supported"));
//return default(T);
}
}
}