只是试图找出如何servicestack.text支持序列化的expando对象和JSON。 我知道,在Expando对象实现了一个IDictionary。 当我序列化和JSON我无法得到正确的类型在反序列化的IDictionary。 为JSON不支持原生类型和servicestack有一个名为JsConfig.IncludeTypeInfo我预计它包括在序列化JSON类型的信息,以使服务栈反序列化到正确类型的另一侧,设置(例如无小数位小数反序列化到一个UINT64)。
反正是有强制servicestack正确的反序列化类型相同使用的expando对象的来源?
PS:我不想使用POCO对象来实现这个,因为我不知道该对象的属性,直到运行时。
下面是一个快速测试显示我的意思。
谢谢
/// <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");
}