繁体   English   中英

序列化对象-GetProperties()导致堆栈溢出?

[英]Serialise object - GetProperties() causes stack overflow?

我正在尝试序列化默认情况下无法序列化的对象的所有属性(该对象的类型为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);

如果我理解正确,您正在尝试序列化共享点对象? 大多数情况下,它将以循环结束。

SPGroup.Users-> SPUser.Groups-> SPGroup.Users-> ...

因此,串行器将在无限循环或堆栈溢出中运行。 更好的方法是构建自己的对象而没有某些导致圆的属性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM