• Advertisement
Sign in to follow this  
  • entry
    1
  • comments
    2
  • views
    319

About this blog

Share experience

 

Entries in this blog

I went looking for Json. But there wasn't a simple Json.
I just wanted to change  Class to Json and change Class back to Json. So I made it myself.

zJson.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
/* code by eekdro@gmail.com */
/* zJson is a simple Json library */
/* Just Class to Json, Json to Class, Haven't Depth*/
 
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
 
namespace AliceUtil
{
    /// <summary>
    /// Json to Class , Class to Json 을 지원하는 Class
    /// </summary>
    public class zJson
    {
 
        public static string MakeJson<T>(List<T> jsonClassList, string FileName ) where T : new()
        {
            string Result = MakeJson(jsonClassList);
            zUt.SaveTextFile(FileName, Result);
            return Result;
            
        }
 
        /// <summary>
        /// List를 Json으로 만들어준다.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonClassList"></param>
        /// <returns></returns>
        public static string MakeJson<T>(List<T> jsonClassList) where T : new()
        {
            string ResultStr = "{\n";
            Type ClassType = typeof(T);
            ResultStr += "\t\"" + ClassType.Name + "\":[";
 
            foreach (T jsonClass in jsonClassList)
            {
                string JsonStr = MakeJson(jsonClass).Replace("\t""\t\t");
                ResultStr += "\t" + JsonStr.Insert(JsonStr.Length - 1"\t"+ ",\n";
            }
 
            if (ResultStr[ResultStr.Length - 2== ',')
                ResultStr = ResultStr.Substring(0, ResultStr.Length - 2);
 
            ResultStr += "\t]\n}";
 
            return ResultStr;
        }
 
        public static string MakeJson<T>(T jsonClass, string FileName) where T : new()
        {
            string Result = MakeJson(jsonClass);
            zUt.SaveTextFile(FileName, Result);
            return Result;
        }
 
        public static string MakeJson<T>(T jsonClass) where T : new()
        {
            string ResultStr = "{\n";
            Type ClassType = typeof(T);
            FieldInfo[] fields = ClassType.GetFields();
            PropertyInfo[] Pinfo = ClassType.GetProperties();
 
            foreach (FieldInfo f in fields)
            {
                if (f.FieldType == typeof(string))
                {
                    string value = f.GetValue(jsonClass) == null ? "" : f.GetValue(jsonClass).ToString();
                    ResultStr += "\t\"" + f.Name + "\":\"" + value + "\",\n";
                }
                else if (f.FieldType == typeof(DateTime))
                    ResultStr += "\t\"" + f.Name + "\":" + ((DateTime)f.GetValue(jsonClass)).Ticks.ToString() + ",\n";
                else if (f.FieldType == typeof(int|| f.FieldType == typeof(long|| f.FieldType == typeof(float|| f.FieldType == typeof(double|| f.FieldType == typeof(bool))
                    ResultStr += "\t\"" + f.Name + "\":" + f.GetValue(jsonClass).ToString() + ",\n";
                else if (f.FieldType == typeof(int[]))
                    ResultStr += "\t\"" + f.Name + "\":" + "[" + string.Join(",", ((int[])f.GetValue(jsonClass)).Select(x => x.ToString()).ToArray()) + "],\n";
                else if (f.FieldType == typeof(long[]))
                    ResultStr += "\t\"" + f.Name + "\":" + "[" + string.Join(",", ((long[])f.GetValue(jsonClass)).Select(x => x.ToString()).ToArray()) + "],\n";
                else if (f.FieldType == typeof(double[]))
                    ResultStr += "\t\"" + f.Name + "\":" + "[" + string.Join(",", ((double[])f.GetValue(jsonClass)).Select(x => x.ToString()).ToArray()) + "],\n";
                else if (f.FieldType == typeof(float[]))
                    ResultStr += "\t\"" + f.Name + "\":" + "[" + string.Join(",", ((float[])f.GetValue(jsonClass)).Select(x => x.ToString()).ToArray()) + "],\n";
                else if (f.FieldType == typeof(bool[]))
                    ResultStr += "\t\"" + f.Name + "\":" + "[" + string.Join(",", ((bool[])f.GetValue(jsonClass)).Select(x => x.ToString()).ToArray()) + "],\n";
                else if (f.FieldType == typeof(string[]))
                    ResultStr += "\t\"" + f.Name + "\":" + "[" + string.Join(",", ((string[])f.GetValue(jsonClass)).Select(x => "\"" + x + "\"").ToArray()) + "],\n";
            }
 
            if (ResultStr[ResultStr.Length - 2== ',')
                ResultStr = ResultStr.Substring(0, ResultStr.Length - 2);
 
            return ResultStr + "\n}";
        }
 
        static string GetTokenString(string Source, string StartStr, string EndStr)
        {
            int Openidx = Source.IndexOf(StartStr);
            int Closeidx = 0;
 
            while (true)
            {
                Openidx = Source.IndexOf(StartStr, Openidx + 1);
                Closeidx = Source.IndexOf(EndStr, Closeidx + 1);
 
                if (Closeidx == -1return "";  // 여기로 온다는 것은 정상적인 Json 이 아니라는 것을 의미한다.
                if (Openidx == -1 || Openidx > Closeidx) break;
            }
            return Source.Substring(1, Closeidx - 1);
        }
 
        public static List<T> PaserListFromFile<T>(string jsonFilename) where T : new()
        {
            return PaserList<T>(zUt.LoadTextFile(jsonFilename));
        }
 
        public static List<T> PaserList<T>(string jsonStr) where T : new()
        {
            List<T> ResultList = new List<T>();
 
            int idx = jsonStr.IndexOf("\"" + typeof(T).Name + "\"");
            if (idx == -1return ResultList;
            jsonStr = jsonStr.Substring(idx);
            idx = jsonStr.IndexOf("[");
            if (idx == -1return ResultList;
            jsonStr = jsonStr.Substring(idx).Trim().Replace("\t""").Replace("\n"""); ;
            jsonStr = GetTokenString(jsonStr, "[""]");
 
            while (true)
            {
                if (jsonStr.Trim() == ""break;
                string ItemStr = GetTokenString(jsonStr, "{""}");
                if (ItemStr == ""break;
                ResultList.Add(Paser<T>(ItemStr));
                jsonStr = jsonStr.Substring(ItemStr.Length + 2);
            }
 
            Console.WriteLine(jsonStr);
 
            return ResultList;
        }
 
        public static T PaserFromFile<T>(string jsonFilename) where T : new()
        {
            return Paser<T>(zUt.LoadTextFile(jsonFilename));
        }
 
        public static T Paser<T>(string jsonStr) where T : new()
        {
            T nJsonClass = new T();
            Type ClassType = typeof(T);
            FieldInfo[] fields = ClassType.GetFields();
            PropertyInfo[] Pinfo = ClassType.GetProperties();
 
            foreach (FieldInfo f in fields)
            {
                int idx = jsonStr.IndexOf("\"" + f.Name + "\"");
                if (idx == -1continue;
                string rs = jsonStr.Substring(idx + ("\"" + f.Name + "\"").Length).Trim().Replace("\t""").Replace("\n""");
                if (rs[0!= ':'continue;
 
                if (f.FieldType == typeof(string))
                {
                    int ix = rs.IndexOf("\"");
                    int chix = rs.IndexOf(",");
                    if (chix != -1 && chix > ix && ix != -1)
                    {
                        rs = rs.Substring(rs.IndexOf("\""+ 1);
                        string value = rs.Substring(0, rs.IndexOf("\""));
                        f.SetValue(nJsonClass, value);
                    }
                    else f.SetValue(nJsonClass, null);
                }
                else if (f.FieldType == typeof(int[]) || f.FieldType == typeof(string[]))
                {
                    int ps = rs.IndexOf("["+ 1;
                    rs = rs.Substring(ps, rs.IndexOf("]"- ps).Trim();
                    if (rs == ""continue;
                    string[] datas = rs.Split(',');
 
                    if (f.FieldType == typeof(int[]))
                    {
                        var temp = new int[datas.Length];
                        for (int n = 0; n < datas.Length; n++) temp[n] = int.Parse(datas[n].Trim());
                        f.SetValue(nJsonClass, temp);
                    }
                    else if (f.FieldType == typeof(string[]))
                    {
                        var temp = new string[datas.Length];
                        for (int n = 0; n < datas.Length; n++) temp[n] = datas[n].Trim().Substring(1, datas[n].Trim().Length - 2);
                        f.SetValue(nJsonClass, temp);
                    }
                }
                else
                {
                    // 마지막이 , } ] 중 가까운 문자위치가 마지막이라고 판단해야된다.
                    int[] EndPos = { rs.IndexOf(","), rs.IndexOf("}"), rs.IndexOf("]") };
                    int ps = 99;
                    foreach (int ix in EndPos)
                        if (ix != -1 && ix < ps) ps = ix;
                    if (ps == -1 || ps == 99continue;
 
                    string value = rs.Substring(1, ps - 1).Trim();
                    if (f.FieldType == typeof(int)) f.SetValue(nJsonClass, int.Parse(value));
 
                    else if (f.FieldType == typeof(DateTime)) f.SetValue(nJsonClass, new DateTime(long.Parse(value)));
                    else if (f.FieldType == typeof(double)) f.SetValue(nJsonClass, double.Parse(value));
                    else if (f.FieldType == typeof(float)) f.SetValue(nJsonClass, float.Parse(value));
                    else if (f.FieldType == typeof(long)) f.SetValue(nJsonClass, long.Parse(value));
                    else if (f.FieldType == typeof(bool)) f.SetValue(nJsonClass, bool.Parse(value));
 
                }
            }
            return nJsonClass;
        }
    }
}
 
 

for coffee 0x4C668AeBB9Facd8ecE8764AaAC48B7186130C411


약간 이해가 안되는 내용이 있다면 나는 Datetime 을 Tick로 보관한다.
이유는 단순하다. 다국적 처리를 할때 Datetime를 String로 바꾸면 문제가 생길 수 있기 때문이다.

If there is something special code, I use Tick to keep Datetime.
The reason is simple. Because changing Datetime to String can cause problem when dealing with multinational process.

Test Code

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
using System;
using System.Collections.Generic;
using System.Text;
using AliceUtil;
 
namespace JsonTest
{
    class Person
    {
        public bool ok;
        public int Id;
        public string Name;
        public DateTime Ddate;
        public int[] intArray = { 1234 };
        public string[] strArray = { "1""2""3""4" };
    }
 
 
    class Program
    {
        static void Main(string[] args)
        {
            List<Person> tbPerson = new List<Person>();
 
            for (int n = 0; n < 3; n++)
            {
                tbPerson.Add(
                    zJson.Paser<Person>(("{'Id' : " + n + ", 'Name' : 'Alex', 'ok':true}").Replace("'""\""))
                    );
            }
 
            string result = zJson.MakeJson<Person>(tbPerson);
            Console.WriteLine(result);
            Console.WriteLine("---------------");
 
            List<Person> PList = zJson.PaserList<Person>(result);
            foreach( Person ps in PList)
            {
                Console.WriteLine(zJson.MakeJson(ps));                
            }
            
        }
    }
}
 
 


 

 

Sign in to follow this  
  • Advertisement