About Monkey 2 › Forums › Monkey 2 Programming Help › Null Variant question
Tagged: reflection, Variants
This topic contains 0 replies, has 1 voice, and was last updated by
Ethernaut
1 year, 3 months ago.
-
AuthorPosts
-
January 15, 2018 at 6:47 am #12867
In the following code, I’d like to detect if the field has a null value WITHOUT knowing the field’s type in advance, in other words, I cannot cast the variant obtained by DeclInfo.Get( instance ) and see if it has a null value.
The goal here is to not Serialize any fields that contain a Null value, and serialize everything else.
(I’m not serializing classes “for real” in this simple example, it’s just adding their class name as the value)Monkey12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485Namespace test#Import "<mojo>"#Reflect mojo..#Reflect std..#Reflect test..Using std..Using mojo..Function Main()Local t := New SerialObjt.Serialize()EndClass SerialObjField value:= 10Field name:= "Test Class"Field image:Image = Null '<------I want the serializer method to skip this empty fieldField color:= Color.RedMethod Serialize:JsonObject()Local obj:= New JsonObjectobj.SetString( "Class", InstanceType.Name )For Local d := Eachin InstanceType.GetDecls()If d.GettableLocal value := d.Get( Self )If value'<----------------------Always contains a DeclInfo, even if the field value is null!obj.SetValue( d.Name, SerializeValue( d, value ) )EndEndNextPrint obj.ToJson()Return objEndMethod SerializeValue:JsonValue( d:DeclInfo, v:Variant )Local newValue:JsonValueLocal info := d.TypeSelect info.NameCase "Float"newValue = New JsonNumber( Cast<Float>( v ) )Case "Double"newValue = New JsonNumber( Cast<Double>( v ) )Case "Int"newValue = New JsonNumber( Cast<Int>( v ) )Case "UInt"newValue = New JsonNumber( Cast<UInt>( v ) )Case "String"newValue = New JsonString( Cast<String>( v ) )Case "Bool"newValue = New JsonBool( Cast<Bool>( v ) )DefaultLocal obj := New JsonObjectIf info.Kind="Class" Or info.Kind="Struct"Local dynamicValue := New JsonString( info.Name )If dynamicValue Then Return dynamicValueElsenewValue = New JsonString( "Serializer: Warning, unhandled scenario found!" )EndEndReturn newValueEndEndIs it doable somehow? Or would this be a feature request?
It’s one of the last missing puzzle pieces I need to have a fully functional Serializer module.Any help appreciated!
-
AuthorPosts
You must be logged in to reply to this topic.