我试图序列化一个对象的所有属性,默认情况下无法序列化(对象是SPGroup类型,它是密封的,没有空的构造函数)所以我复制了所有的属性从我将序列化的对象。
我使用下面的代码从属性中获取数据:
private dynamic GetSerializableProperties<T>(T objToCopy, dynamic dataContainer = null)
{
// Copy the properties into dataContainer, if it's not set
if (Object.ReferenceEquals(null, dataContainer))
{
dataContainer = new ExpandoObject() as IDictionary<string, object>;
}
// copy base class properties.
var objToCopyType = objToCopy.GetType();
foreach (PropertyInfo propertyInfo in objToCopyType.GetProperties())
{
// Get the correct property
PropertyInfo propertyInfoValue = objToCopyType.GetProperty(propertyInfo.Name);
// Get the value of the property
var value = objToCopyType.GetProperty(propertyInfo.Name).GetValue(objToCopy, null); // propertyInfoValue.GetValue(objToCopy, null);
// Create the ID for the dictionary, set to name/random string for easy viewing
string propertyKeyName = CreateSafeName(dataContainer, propertyInfo.Name);
// Create a property with the required name then add data
((IDictionary<String, Object>)dataContainer)[propertyInfo.Name] = new DataContainer(propertyInfo.Name, propertyInfo, propertyInfoValue, value);
}
return dataContainer;
}
当我查看我创建的动态对象时,我会看到我想要的所有属性,即属性用户包含用户列表。下一步是序列化这个错误发生的数据。
dynamic serializableObject = GetSerializableProperties<T>(serializableObjectx);
var test = serializableObject as IDictionary<string, Object>;
var test2 = test.Values.ElementAt(2) as DataContainer; // This property contains a property that is causing the issue I believe
var obj = JsonConvert.SerializeObject(test2, Newtonsoft.Json.Formatting.Indented);
我得到的错误是:
Cannot evaluate expression because the current thread is in a stack overflow state.
我认为此评论下面的代码需要更改:
var value = objToCopyType.GetProperty(propertyInfo.Name).GetValue(objToCopy, null); // propertyInfoValue.GetValue(objToCopy, null);
答案 0 :(得分:0)
如果我说得对,你试图序列化sharepoint对象?大部分时间它将以流通结束。
SPGroup.Users - &gt; SPUser.Groups - &gt; SPGroup.Users - &gt; ...
因此序列化器将在无限循环或堆栈溢出中运行。更好的方法是构建自己的对象,而没有导致圆形的某些属性。