setting fields of object using traits

Ram_B via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Sep 20 12:45:00 PDT 2016


I'm trying to set fields of object from JSON with traits library. 
How i can to it properly?

import std.stdio;
import std.json;
import std.traits;
import std.meta:  Alias;

class Obj{
	void fromJSON(this T)(JSONValue j){
		foreach(field; FieldNameTuple!T){
			alias member = Alias!(__traits(getMember, T, field));
			static if (__traits(hasMember, member, "fromJSON")){
				member.fromJSON(j[field]);
			} else {
				member = j[field];
			}
		}
	}
}

class A : Obj{
	int a,b;
	C c;
	this(){
		c = new C();
	}
	
}

class C : Obj{
	int a;
	this(){
		a = 0;
	};
}

int main(string[] argv)
{
	string s = "{\"a\": 1, \"b\": 2, \"c\": {\"a\": 3} }";
	JSONValue j = parseJSON(s);
	A a = new A();
	a.fromJSON(j);
	writeln(a.b);
	readln();
     return 0;
}

main.d(14): Error: need 'this' for 'a' of type 'int'
main.d(14): Error: need 'this' for 'b' of type 'int'
main.d(12): Error: template main.Obj.fromJSON cannot deduce 
function from argument types !(c)(JSONValue), candidates are:
main.d(8):        main.Obj.fromJSON(this T)(JSONValue j)
main.d(41): Error: template instance main.Obj.fromJSON!(A) error 
instantiating



More information about the Digitalmars-d-learn mailing list