1 // Custom JSON Convertor 2 // ユーザーは、任意の型をJSONへ変換するための変換器を定義できる 3 static struct CustomJSONConvertor 4 { 5 static { mixin JSONEnv!null _dummy; } 6 7 static JSONValue toJSONValueImpl(string str) 8 { 9 return _dummy.toJSONValueImpl("Custom Convertor-String : " ~ str); 10 } 11 12 13 static void fromJSONValueImpl(JSONValue json, ref string str) 14 { 15 assert(json.type == JSON_TYPE.STRING, "Error"); 16 str = json.str.find(" : ").drop(3); 17 } 18 } 19 20 21 // グローバルなsetterとgetterだと仮定 22 static struct Foo 23 { 24 int gloF() @property { return _gloF; } 25 void gloF(int a) @property { _gloF = a; } 26 27 static int _gloF = 12345; 28 } 29 30 31 // グローバル変数だと仮定 32 static string gloG = "global variable"; 33 34 35 // JSONへ変換したり、JSONから変換する対象のオブジェクト 36 static struct S1 37 { 38 // JSON Convertorの定義 39 // 通常はモジュールで定義すればよい 40 static { 41 mixin JSONEnv!CustomJSONConvertor; 42 } 43 44 45 // refで返すプロパティ 46 ref real flt() @property 47 { 48 return _flt; 49 } 50 51 52 // getter 53 int[] arr() @property 54 { 55 return _arr; 56 } 57 58 // setter 59 void arr(int[] arr) @property 60 { 61 _arr = arr; 62 } 63 64 65 // JSONでのオブジェクトの定義 66 mixin JSONObject!("intA", a, // メンバ変数 67 "strB", "b", // メンバ変数(文字列) 68 "fltC", flt, // refを返すメンバ関数(プロパティ) 69 "arrD", "arr", // setter, getter 70 "aasE", "aas", // static setter, getter 71 "gloF", "Foo.init.gloF", // global setter, getter 72 "gloG", gloG, // グローバル変数など外部スコープの変数 73 ); 74 75 76 private: 77 int a; 78 string b; 79 real _flt; 80 int[] _arr; 81 82 83 static: 84 85 // staticなgetter 86 int[int] aas() @property 87 { 88 return [1 : 2, 2 : 3, 3 : 4, 4 : 5]; 89 } 90 91 92 // staticなsetter 93 void aas(int[int] aa) @property 94 {} 95 } 96 97 auto s1 = S1(12, "foo", 2.0, [1, 2, 3, 4]); 98 auto jv = S1.toJSONValue(s1); 99 100 auto jvtext = parseJSON(`{"gloF":12345,"strB":"Custom Convertor-String : foo","fltC":2,"gloG":"Custom Convertor-String : global variable","intA":12,"aasE":{"4":5,"1":2,"2":3,"3":4},"arrD":[1,2,3,4]}`); 101 assert(toJSON(&jv) == toJSON(&jvtext)); 102 103 auto s2 = S1.fromJSONValueImpl(jv); 104 auto s3 = S1.fromJSONValueImpl(jvtext); 105 106 assert(s1 == s2); 107 assert(s2 == s3); 108 109 assert(Foo.init.gloF == 12345); 110 assert(gloG == "global variable");
任意のユーザー定義型をJSONでのObjectに変換する際に便利なテンプレート