How do you get System.Web.Script.javascriptSerializer to ignore a property?
Asked Answered
C

1

11
[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
}
Click answered 23/1, 2010 at 21:41 Comment(2)
Can you show a code sample where you call ToJson? It does not throw when I try it out...Phalan
I suspect at least some code has been omitted, as there is no nice way of setting the values - ?Sienese
S
15

Normally I would suggest telling it to ignore parent properties (which create cycles) - in this case by adding [ScriptIgnore] - but I can't see anything other than basic members - is this class by itself enough to cause the error?

Sienese answered 23/1, 2010 at 21:49 Comment(1)
apparently I left that one property out, I thought that maybe the javascriptSerializer would pay attention to the ISerializable interfaceClick

© 2022 - 2024 — McMap. All rights reserved.