Hi
I am trying to use introspection to serialise a hierarchical class structure for export via JSON - like a prefs file.
I seem to be OK with creating JSON strings for most properties, including primitives, dates, classes and arrays of primitives, but it all seems to fail with arrays of classes - I keep getting a TypeMismatchException when trying to assign the propertyInfo.value (which should be the array of classes) back to a locally dim’d array of the same classes e.g. as in
dim ss() as jsonRecord = pi.value(o) //where pi is the propertyInfo, o is the object that the property sits in and jsonRecord is the expected class.
The strange thing is that I can export to JSON OK - the JSON.toString is fine. I can import that string to recreate the classes just fine - and all the classes are in their correct position/content etc. But when I try to re-export to JSON again I get the TypeMismatch error above. It is as if something in the re-creation of the classes hasn’t completed properly - perhaps in the constructor.invoke command in Introspection.constructorInfo.
Has anyone successfully done this that can share some code?
Yes. In fact, I have a whole open-source project to do just this:
https://github.com/ktekinay/Data-Serialization
Brilliant! Thanks Kem - looks comprehensive - I’ll let you know how I get on with it.
Well, it took a while but I eventually found the solution in your code (I couldn’t apply your classes directly as I wanted a different JSON format)
'// You can't go from a Variant that holds an array of some objects directly to
'// an Object array, but you can go from an Auto that holds that array
'// to an Object array. Am I exploiting a bug? Maybe, but it works.
'dim a as Auto = v
'dim arr() as Variant = a
'for i as integer = 0 to arr.Ubound
'elementsChild.Append ToJSONValue( arr( i ), "" )
'next
The trick of loading the propertyInformation.value via an Auto before loading into a Variant did the trick and prevented the TypeMisMatch exception. In my code it looks like this:
[code] dim a as auto = pi.value(o) // - to avoid typeMismatchException after reload
dim ss() as variant = a
//need to cycle through the array to append each one.
for i as integer = 0 to ss.ubound
js.value( str(i) ) = jsonRecord.get_json( ss(i), onlyPrefixed, compact)
next[/code]
A bug I think.