Usage of custom class with JSONValue
Edwin van Leeuwen via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Mar 24 01:24:46 PDT 2016
On Thursday, 24 March 2016 at 08:15:12 UTC, Andre wrote:
> Hi,
>
> I have a class which has already an alias this to a string
> array,
> so I can use it in a foreach loop.
>
> class MyClass
> {
> string[] _data;
> alias _data this;
> // ...
> }
>
> void main()
> {
> import std.json;
> auto jsValue = JSONValue(new MyClass());
> }
>
> For some generic code I need an implicit conversion of MyClass
> so I can
> use it for a JSONValue. For the coding above I receive a
> compiler error:
> static assert "unable to convert type "MyClass" to json"
JSONValue only works with the build in types, not with user
defined types. Either you define a specific function for the
class that returns a JSONValue. Easiest way to do that would be
to build an associative array with strings as keys with the
names, and JSONValues as values and turn that into JSONValue,
i.e. (untested):
class MyClass
{
string[] _data;
alias _data this;
// ...
JSONValue toJSON()
{
JSONValue[string] aa;
JSONValue[] dataJSON = _data.map!((a) => JSONValue(a)).array;
aa["data"] = JSONValue(dataJSON);
return JSONValue(aa);
}
}
Alternatively there are multiple serialization libraries that
will allow you to turn any user defined type from and to
JSONValues.
https://code.dlang.org/packages/painlessjson
https://code.dlang.org/packages/jsonizer
Cheers, Edwin
More information about the Digitalmars-d-learn
mailing list