gpt4 book ai didi

c# - 你如何让 System.Web.Script.javascriptSerializer 忽略一个属性?

转载 作者:可可西里 更新时间:2023-11-01 08:42:18 25 4
gpt4 key购买 nike

[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] - 但除了基本成员之外,我看不到任何东西 - 这个类本身是否足以导致错误?

关于c# - 你如何让 System.Web.Script.javascriptSerializer 忽略一个属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2124864/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com