c# – 如何让System.Web.Script.javascriptSerializer忽略属性?

前端之家收集整理的这篇文章主要介绍了c# – 如何让System.Web.Script.javascriptSerializer忽略属性?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
[Serializable]
public class ModelResource:ISerializable
{
   public Int64 Ore { get; private set; }
   public Int64 Crystal { get; private set; }
   public Int64 Hydrogen { get; private set; }
   //needs to be ignored
   public Int64 Total { get { return Ore + Hydrogen + Crystal; } }
   public string ResourceType { get; private set; }
   public Int64 HerculesNeeded { get { return Total / 25000; } }
   public Int64 AtlasNeeded { get { return Total / 5000; } }

   public bool IsPlanet { get { return ResourceType == "Planet"; } }
   //causes serializer to stackoverflow
   public ModelResource MakeChild {get{return new ModelResource(Ore/2,Crystal/2,Hydrogen/2);}}


    public string ToJson()
    {
        var jss = new System.Web.Script.Serialization.JavaScriptSerializer(new SimpleTypeResolver());
        return jss.Serialize(this); //throws recursion limit exceed exception
    }
    #region ISerializable Members

    public void GetObjectData(SerializationInfo info,StreamingContext context)
    {
        info.AddValue("Ore",Ore);
        info.AddValue("Crystal",Crystal);
        info.AddValue("Hydrogen",Hydrogen);
        info.AddValue("ResourceType",ResourceType);
    }
    private ModelResource(SerializationInfo si,StreamingContext context)
    {
        Ore = si.GetInt64("Ore");
        Crystal = si.GetInt64("Crystal");
        Hydrogen = si.GetInt64("Hydrogen");
        ResourceType = si.GetString("ResourceType");
    }


    #endregion
}

解决方法

通常我建议告诉它忽略父属性(创建循环) – 在这种情况下,添加 [ScriptIgnore] – 但我看不到除基本成员之外的其他东西 – 这个类本身足以导致错误
原文链接:https://www.f2er.com/csharp/96893.html

猜你在找的C#相关文章