我对 wcf 服务(JSON 输出)的序列化有疑问。我使用 dynamicobject 为我的 REST 服务返回 ligth JSON。
此代码返回一个空结果(无法序列化):
public DynamicJsonObject DoWork()
{
dynamic result = new DynamicJsonObject();
result.values = new List<int>() { 1, 2 };
}
但这段代码完美无缺
public DynamicJsonObject DoWork()
{
dynamic result = new DynamicJsonObject();
result.values = 1;
}
我的 DynamicJsonObject 类是:
[Serializable]
public class DynamicJsonObject : DynamicObject, ISerializable
{
private IDictionary<String, Object> Dictionary { get; set; }
public DynamicJsonObject()
{
Dictionary = new Dictionary<String, Object>();
}
public DynamicJsonObject(SerializationInfo info, StreamingContext context)
{
Dictionary = new Dictionary<String, Object>();
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
var hasKey = Dictionary.ContainsKey(binder.Name);
result = hasKey ? Dictionary[binder.Name] : null;
return hasKey;
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
Dictionary[binder.Name] = value;
return true;
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
foreach (String key in Dictionary.Keys)
{
info.AddValue(key.ToString(), Dictionary[key]);
}
}
}
所以我得到了这个错误 Error 324 (net::ERR_EMPTY_RESPONSE) 而不是这个 JSON 结果 {values: [1,2]}