1 // Written in the D programming language. 2 /* 3 * Copyright 2015 Jaypha 4 * 5 * Distributed under the Boost Software License, Version 1.0. 6 * (See http://www.boost.org/LICENSE_1_0.txt) 7 * 8 * Authors: Jason den Dulk 9 */ 10 11 module jaypha.json; 12 13 //-------------------------------------------------------------------------- 14 // Functons for comverting from a JSON value. 15 16 import std.array; 17 import std.conv; 18 public import std.json; 19 import std.traits; 20 21 T fromJSON(T)(JSONValue jVal) if (isScalarType!T || isSomeString!T) 22 { 23 final switch (jVal.type) 24 { 25 case JSON_TYPE.TRUE: 26 return to!T(true); 27 case JSON_TYPE.FALSE: 28 return to!T(false); 29 case JSON_TYPE.INTEGER: 30 return to!T(jVal.integer); 31 case JSON_TYPE.UINTEGER: 32 return to!T(jVal.uinteger); 33 case JSON_TYPE.FLOAT: 34 return to!T(jVal.floating); 35 case JSON_TYPE.STRING: 36 return to!T(jVal.str); 37 case JSON_TYPE.OBJECT: 38 case JSON_TYPE.ARRAY: 39 assert(false); 40 case JSON_TYPE.NULL: 41 return T.init; 42 } 43 } 44 45 //-------------------------------------------------------------------------- 46 47 T[] fromJSON(T:T[])(JSONValue jVal) if (!isSomeString!(T[])) 48 { 49 assert(jVal.type == JSON_TYPE.ARRAY); 50 auto app = appender!(T[])(); 51 foreach (val; jVal.array) 52 app.put(fromJSON!T(val)); 53 return app.data; 54 } 55 56 //-------------------------------------------------------------------------- 57 58 T[string] fromJSON(T:T[string])(JSONValue jVal) 59 { 60 assert(jVal.type == JSON_TYPE.OBJECT); 61 T[string] ret; 62 foreach (idx,val; jVal.object) 63 ret[idx] = fromJSON!T(val); 64 return ret; 65 }