如何让 ServiceStack 序列化/反序列化具有正确类型的 Expando 对象

2023-11-30

只是想弄清楚 servicestack.text 支持将 Expando 对象序列化到 json 或从 json 序列化的情况如何。我知道 Expando 对象实现了 IDictionary。当我序列化到 json 或从 json 序列化时,我无法在反序列化的 IDictionary 中获取正确的类型。由于 Json 本身不支持类型,并且 servicestack 有一个名为 JsConfig.IncludeTypeInfo 的设置,我希望它在序列化的 json 中包含类型信息,以使服务堆栈能够反序列化为另一侧的正确类型(例如,没有小数位的小数)被反序列化为 uint64)。

无论如何,是否有强制服务堆栈使用扩展对象正确反序列化与源相同的类型?

Ps:我不想使用 poco 对象来实现此目的,因为直到运行时我才知道该对象的属性。

下面是一个快速测试,显示了我的意思。

Thanks

/// <summary>
/// Test servicestack serialisation
/// I was expecting that IncludeTypeInfo=true would always add the type info
/// so when you deserialise into a IDictionary<string,object> servicerstack
/// would have enough information to convert to the expected type
/// </summary>
[Test]
public void TestDynamicSerialization()
{
    JsConfig.Reset();
    JsConfig.IncludeNullValues = true;
    JsConfig.IncludeTypeInfo = true;
    JsConfig.EmitCamelCaseNames = false;
    JsConfig.ConvertObjectTypesIntoStringDictionary = true;
    JsConfig.PropertyConvention = JsonPropertyConvention.Lenient;
    JsConfig.TryToParsePrimitiveTypeValues = true;

    // create an expando object
    dynamic obj = new ExpandoObject();

    // cast as a idictionary and set two decimals, one with decimnal places and one without
    var objDict = (IDictionary<string, object>)obj;
    objDict["decimal1"] = 12345.222M;
    objDict["decimal2"] = 12345M;

    Assert.AreEqual(typeof(decimal), objDict["decimal1"].GetType());
    Assert.AreEqual(typeof(decimal), objDict["decimal2"].GetType());

    // serialise to json
    var json = JsonSerializer.SerializeToString(obj);

    //deserialise to a a IDictionary<string,object>
    var deserialisedDict = JsonSerializer.DeserializeFromString<IDictionary<string, object>>(json);

    // make sure we got the expected types
    Assert.AreEqual(typeof(decimal), deserialisedDict["decimal1"].GetType());
    Assert.AreEqual(typeof(decimal), deserialisedDict["decimal2"].GetType(), "Fails because type is UInt64 expected decimal");


}

NuGet 上的 ServiceStack.Text 是一个 .NET 3.5 dll,没有对 Dynamic/Expando 的隐式支持。您仍然可以使用JsonObject动态解析 JSON。

在 ServiceStack.Text 的 .NET 4.0 版本中,您可以使用DynamicJson它将对 JSON 对象的访问包装在 Dynamic 类中。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何让 ServiceStack 序列化/反序列化具有正确类型的 Expando 对象 的相关文章

随机推荐