简体   繁体   中英

Serialize a COM object to JSON?

I have set a reference in C# code to a COM DLL (compiled from VB6).

I am trying to serialize a COM object from a type in that DLL using JSON.NET (NewtonSoft).

Code that I've tried so far:

    var settings = new JsonSerializerSettings
    {
        Formatting = Formatting.Indented,                
    };

    var serializer = JsonSerializer.Create(settings);

    using (var gz = new GZipStream(File.OpenWrite(filespec), CompressionMode.Compress))
    using (var sw = new StreamWriter(gz))
    using (var writer = new JsonTextWriter(sw))
    {
        serializer.Serialize(writer, objectToSerialize);
    }

The resulting file contains only:

{}

whereas for a native class this code would produce a comprehensive serialization.

The actual objectToSerialize has a number of object properties several layers deep.

Is there some way to get the serializer to correctly work with this type of class?

Notes:

  • The DLL is loaded using a standard RCW interop DLL autogenerated by Visual Studio 2015

  • As is typical for this type of object, the runtime property inspector shows a "Native View" and a "Dynamic View" of the properties of the object. I have a suspicion that this treatment of the object is similar to what JSON.NET is doing, and if it only looks at the "native" view maybe it missed all the real properties. On the other hand VS2015 obviously can inspect the real object thus I'm hopeful that this can be made to work.

Thanks

This can work as long as the object being serialized uses the type of the interop-generated class - not an interface.

Say in the example in the question that the type of objectToSerialize was SomeType in the original VB6 code. In the Visual Studio object browser you could see several rough equivalents in the interop library:

  • Interface SomeType

  • Interface _SomeType

  • Class SomeTypeClass

It is the last one which must be used for serialization.

Now, curiously even though SomeType is an interface you can create a new one and operate on that resulting object in an apparently normal way. But also apparent is that this object won't allow the type of reflection used by JSON.net serialization.

Note - ObjectDumper should behave in the same way wrt these types. So all this doesn't seem to be a specific JSON.NET limitation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM