回答編集履歴

2

使用例を追加

2018/01/26 07:51

投稿

Ushimaru
Ushimaru

スコア69

test CHANGED
@@ -53,3 +53,159 @@
53
53
  を分けて考えるとより回答が付きやすくなるかと思います。
54
54
 
55
55
  ご参考までに!
56
+
57
+
58
+
59
+ ---
60
+
61
+ さらに追記:
62
+
63
+ 上記のスクリプトを使わせてもらう場合、ラップした方が使いやすいと思うので例を載せておきます。
64
+
65
+ ```
66
+
67
+ // ラップ例
68
+
69
+ public class JsonReader
70
+
71
+ {
72
+
73
+ JSONObject jsonObject;
74
+
75
+
76
+
77
+ public JsonReader(string jsonText)
78
+
79
+ {
80
+
81
+ this.jsonObject = new JSONObject(jsonText);
82
+
83
+ }
84
+
85
+
86
+
87
+ // 内部的に使います。指定したキーが存在しなければ例外を発生させています。
88
+
89
+ JSONObject GetField(string key)
90
+
91
+ {
92
+
93
+ if (!jsonObject.HasField(key)) {
94
+
95
+ var message = "Jsonオブジェクトにキー[" + key + "]が見つかりませんでした。";
96
+
97
+ throw new KeyNotFoundException(message);
98
+
99
+ }
100
+
101
+ return jsonObject.GetField(key);
102
+
103
+ }
104
+
105
+
106
+
107
+ public string GetString(string key)
108
+
109
+ {
110
+
111
+ return GetField(key).str;
112
+
113
+ }
114
+
115
+
116
+
117
+ public int GetInt(string key)
118
+
119
+ {
120
+
121
+ return (int)GetField(key).i;
122
+
123
+ }
124
+
125
+
126
+
127
+ // 基本型以外もすきな方法で取得できます。
128
+
129
+ public DateTime GetDateTime(string key)
130
+
131
+ {
132
+
133
+ var dateTimeString = GetString(key);
134
+
135
+ DateTime result;
136
+
137
+ if (!DateTime.TryParse(dateTimeString, out result)) {
138
+
139
+ var message = "文字列「" + dateTimeString + "」を日付時間型に変換できませんでした。";
140
+
141
+ throw new ArgumentException(message);
142
+
143
+ }
144
+
145
+ return result;
146
+
147
+ }
148
+
149
+
150
+
151
+ public DateTime GetDate(string key)
152
+
153
+ {
154
+
155
+ return GetDateTime(key).Date;
156
+
157
+ }
158
+
159
+ }
160
+
161
+ ```
162
+
163
+ ```
164
+
165
+ // 使用例
166
+
167
+ public class Hoge
168
+
169
+ {
170
+
171
+ // テストのために適当なJsonを読み込ませておく
172
+
173
+ JsonReader fuga = new JsonReader("{\"name\": \"名前\", \"birthday\": \"1956-07-08\"}");
174
+
175
+
176
+
177
+ public string Name {
178
+
179
+ get { return fuga.GetString("name"); }
180
+
181
+ }
182
+
183
+
184
+
185
+ public DateTime BirthDay {
186
+
187
+ get { return fuga.GetDate("birthday"); }
188
+
189
+ }
190
+
191
+
192
+
193
+ public int Age {
194
+
195
+ get {
196
+
197
+ var birthday = this.BirthDay;
198
+
199
+ var today = DateTime.Today;
200
+
201
+ var age = today.Year - birthday.Year;
202
+
203
+ return age - (birthday > today.AddYears(age) ? 1 : 0);
204
+
205
+ }
206
+
207
+ }
208
+
209
+ }
210
+
211
+ ```

1

追記

2018/01/26 07:51

投稿

Ushimaru
Ushimaru

スコア69

test CHANGED
@@ -31,3 +31,25 @@
31
31
  float weight = jsonObj.GetField("weight").f;
32
32
 
33
33
  ```
34
+
35
+
36
+
37
+ ---
38
+
39
+ 追記:
40
+
41
+ 問題の本質は「Jsonのシリアライズ/デシリアライズをすっきり書きたい」ことであり、「匿名クラスを定義したい」ことではないと思います。
42
+
43
+
44
+
45
+ 上記の解決策が最善とは限りませんが、
46
+
47
+ ・問題の本質
48
+
49
+ ・現在採用している、もしくは採用したいと思っている手段
50
+
51
+ ・上記手段の問題点
52
+
53
+ を分けて考えるとより回答が付きやすくなるかと思います。
54
+
55
+ ご参考までに!