I am looking for the Json class in the haxe package on Github, but for some reason I cannot seem to find it! I was thinking of implementing a Generic type into the encode function as a “helper” function if you want to explicitly provide a Class for the given JSON to cast on before it’s returned. This would be very helpful but I can’t find the source code anywhere…
I was thinking something along the lines of this:
public static function encode<T>(data:String):T
{
var instance = Type.createInstance(T);
var fields:Array<String> = Type.getClassFields(instance);
for (field in fields)
{
Reflect.setField(instance, field, getValueOfFieldInData(data));
}
return cast(instance, T);
}
And just wrap that around the existing code… wherever it is… obviously I would need to test it because I don’t even know if that will work, but it would save a hell of a lot of time.
Nevermind, found it: https://github.com/HaxeFoundation/haxe/blob/development/std/haxe/Json.hx Posted the topic before searching…
EDIT: Now I am having a difficult time:
/**
Parses the given JSON-encoded `text` and returns the given Class type
with the information found in the text.
If given `text` is not valid JSON, an exception will be thrown.
**/
public static function decode<T>(cls:Class<T>, text:String):T
{
var casted = Type.createEmptyInstance(cls);
var obj = Json.parse(text);
var fields = Reflect.fields(obj);
for (item in fields)
{
trySetField(casted, item, Reflect.field(obj, item));
}
return casted;
}
private static function trySetField<T>(obj:Class<T>, field:String, value:Dynamic):Void
{
try
{
Reflect.setField(obj, field, value);
}
catch (msg:String)
{
}
}
The following code results in the following error:
encode.T should be Class<Unknown<0>>
for function argument 'obj'
I am really not sure how to solve this…
THE ULTIMATE EDIT OF ALL ULTIMATES: I am just going to create a new bloody class and copy the WORKING code…
Okay, now I truly do have a problem which I would like to dicuss because this is rather amusing:
http://try.haxe.org/#f42f6 This is some test code, and you can build and it works. It parses everything correctly as you would expect.
Now look at this:
The exact same code (just with traces) purely to try and resolve this problem, but I don’t understand why it works on the try.haxe.org website, and not in a standalone Flash Player… So confusing…
Tested in Neko, and prints out correctly … Obviously just a problem with Flash Player