Is there a way to read serialized C # objects in Python?

I have a binary file containing C # serialized objects.

I can read the contents using python, but get results similar to:

'T\x00\x00\x00Test.Jobs.GenerateJobRequest, POC.Server\xca\x02-\xa2\x02\t\x82\x01\x06\x1a\x04myahR\x1d\x08\xfe\xff\xff\xff\xff\xff\xff\xff\xff\x01\x12\x10Data Lite Exportp\t\n\x16Do_Ko_Change-Job__ID_23\x10\x0c\x18\xa7\xb9\x18(\x012\x00:\x00H\xbc\x08') 

Is there a way to deserialize this object in python?

I agree that this is not an optimal solution, and JSON, XML will be better. However, I do not control the process that serializes the data; I am just a consumer.

+4
source share
4 answers

It is not clear from your question which version of Python (CPython, Jython, IronPython) you are using. But I assume that you are using CPython, as for IronPython this will be trivial.

There is a library for CPython, Python.NET . It serves as a bridge between .NET and Python and works very well. Even generics are supported. Although it looks like it is no longer being kept active, I have been using it for a while. It works like a charm.

You will need Visual Studio to compile it, but it will probably work with Visual Studio Express (although I don't know).

With this, you can import any .NET-dll. Assuming you can deserialize it in C #, you can also deserialize it in Python.

+2
source

There is no official documented binary serialized data format. The closest thing I came across was http://primates.ximian.com/~lluis/dist/binary_serialization_format.htm . Thus, there is a small opportunity to get a Python package from a third party who will do it for you. Even if this happens, its likelihood may be interrupted in the future.

If you want to stick with Binary Serialization, it's best to use IronPython and rely on the CLR to serialize data.

Also, use either SOAP or XML Serialization to ensure compatibility outside the CLR.

+1
source

As stated above, you can use pythonnet and clr. its not really python, but it should get the right stuff ...

 import clr import System #requires pythonnet installed -> pip install pythonnet clr.AddReference("YourDLLAssemblyName") # usually requires dll to be within directory from System.Runtime.Serialization.Formatters.Binary import BinaryFormatter from System.IO import FileStream,FileMode,FileAccess,FileShare filepath = '<PathToYourDataFile>' serializer = BinaryFormatter() reader = FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.None) data = serializer.Deserialize(reader) print(data, data.GetType()) #from here on you can propably go on via reflection or try to cast it reader.Close() 
+1
source

No. This cannot be done the way you want, at any reasonable time.

You need to deserialize it to XML and then use something like this to turn it into python lists / maps.

0
source

All Articles