[Python] How can I Deserialize MessagePack from Json (via Python) with a DateTime property?

Discussão em 'Python' iniciado por Stack, Fevereiro 17, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to deserialize a MessagePack message generated from a python client to a .net object. Running into some trouble with DateTimes. Interestingly staying in the C# arena it doesn't work either.

    Newtonsoft is able to deserialize the json correctly. Although MessagePack's ToJson returns valid Json, deserializing the object fails.

    [DataContract]
    public class TestClass
    {
    [DataMember]
    public string TestPropertyA { get; set; }
    [DataMember]
    public string TestPropertyB { get; set; }
    [DataMember]

    public DateTime EventTimeStamp { get; set; }
    }

    //Move from Json string to an object
    String jsonStringFromPython = "{\"TestPropertyA\":\"Hello\",\"TestPropertyB\":\"World\",\"EventTimeStamp\":\"2019-05-02T16:04:30.7812850Z\"}";
    TestClass anObject = JsonConvert.DeserializeObject<TestClass>(jsonStringFromPython);

    //Generate byte arrays for Messagepack
    Byte[] arrFromAString = MessagePackSerializer.FromJson(jsonStringFromPython);
    Byte[] arrFromAnObj = MessagePackSerializer.Serialize<TestClass>(anObject);
    CompositeResolver.RegisterAndSetAsDefault(PrimitiveObjectResolver.Instance, ContractlessStandardResolver.Instance);

    //Message pack understands the object-generated byte array
    var backtoobject = MessagePackSerializer.Deserialize<TestClass>(arrFromAnObj);

    //Message pack DOES NOT UNDERSTAND the string-generated byte array and fails with code is invalid. code:188 format:fixstr'
    var backtoobject2 = MessagePackSerializer.Deserialize<TestClass>(arrFromAString);


    The last line of code above fails, but all works flawlessly if I drop the DateTime property from the string/object.

    Continue reading...

Compartilhe esta Página