teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

2

使用例を追加

2018/01/26 07:51

投稿

Ushimaru
Ushimaru

スコア69

answer CHANGED
@@ -25,4 +25,82 @@
25
25
  ・現在採用している、もしくは採用したいと思っている手段
26
26
  ・上記手段の問題点
27
27
  を分けて考えるとより回答が付きやすくなるかと思います。
28
- ご参考までに!
28
+ ご参考までに!
29
+
30
+ ---
31
+ さらに追記:
32
+ 上記のスクリプトを使わせてもらう場合、ラップした方が使いやすいと思うので例を載せておきます。
33
+ ```
34
+ // ラップ例
35
+ public class JsonReader
36
+ {
37
+ JSONObject jsonObject;
38
+
39
+ public JsonReader(string jsonText)
40
+ {
41
+ this.jsonObject = new JSONObject(jsonText);
42
+ }
43
+
44
+ // 内部的に使います。指定したキーが存在しなければ例外を発生させています。
45
+ JSONObject GetField(string key)
46
+ {
47
+ if (!jsonObject.HasField(key)) {
48
+ var message = "Jsonオブジェクトにキー[" + key + "]が見つかりませんでした。";
49
+ throw new KeyNotFoundException(message);
50
+ }
51
+ return jsonObject.GetField(key);
52
+ }
53
+
54
+ public string GetString(string key)
55
+ {
56
+ return GetField(key).str;
57
+ }
58
+
59
+ public int GetInt(string key)
60
+ {
61
+ return (int)GetField(key).i;
62
+ }
63
+
64
+ // 基本型以外もすきな方法で取得できます。
65
+ public DateTime GetDateTime(string key)
66
+ {
67
+ var dateTimeString = GetString(key);
68
+ DateTime result;
69
+ if (!DateTime.TryParse(dateTimeString, out result)) {
70
+ var message = "文字列「" + dateTimeString + "」を日付時間型に変換できませんでした。";
71
+ throw new ArgumentException(message);
72
+ }
73
+ return result;
74
+ }
75
+
76
+ public DateTime GetDate(string key)
77
+ {
78
+ return GetDateTime(key).Date;
79
+ }
80
+ }
81
+ ```
82
+ ```
83
+ // 使用例
84
+ public class Hoge
85
+ {
86
+ // テストのために適当なJsonを読み込ませておく
87
+ JsonReader fuga = new JsonReader("{\"name\": \"名前\", \"birthday\": \"1956-07-08\"}");
88
+
89
+ public string Name {
90
+ get { return fuga.GetString("name"); }
91
+ }
92
+
93
+ public DateTime BirthDay {
94
+ get { return fuga.GetDate("birthday"); }
95
+ }
96
+
97
+ public int Age {
98
+ get {
99
+ var birthday = this.BirthDay;
100
+ var today = DateTime.Today;
101
+ var age = today.Year - birthday.Year;
102
+ return age - (birthday > today.AddYears(age) ? 1 : 0);
103
+ }
104
+ }
105
+ }
106
+ ```

1

追記

2018/01/26 07:51

投稿

Ushimaru
Ushimaru

スコア69

answer CHANGED
@@ -14,4 +14,15 @@
14
14
  string name= jsonObj.GetField("name").str;
15
15
  int age = (int)jsonObj.GetField("age").i;
16
16
  float weight = jsonObj.GetField("weight").f;
17
- ```
17
+ ```
18
+
19
+ ---
20
+ 追記:
21
+ 問題の本質は「Jsonのシリアライズ/デシリアライズをすっきり書きたい」ことであり、「匿名クラスを定義したい」ことではないと思います。
22
+
23
+ 上記の解決策が最善とは限りませんが、
24
+ ・問題の本質
25
+ ・現在採用している、もしくは採用したいと思っている手段
26
+ ・上記手段の問題点
27
+ を分けて考えるとより回答が付きやすくなるかと思います。
28
+ ご参考までに!