I have a simple model for testing:

[Serializable]
public class PageModel : IPageModel
    {
        Guid _guid;

        public Guid GUID
        {
            get
            {
                if (_guid == Guid.Empty)
                    _guid = Guid.NewGuid();
                return _guid;
            }
            set
            {
                _guid = value;
            }
        }
        public bool ShouldSerializeGUID()
        {
            return false; // GUID still serialized!
        }
}

I try to serialize it like this:

    JavaScriptSerializer serializer = new JavaScriptSerializer();

    string jsonData= serializer.Serialize(pageModelInstance);

Can someone please tell me what I am missing here?

Is there another way to do conditional serialization?

有帮助吗?

解决方案

Basically, JavaScriptSerializer doesn't support that pattern of conditional serialization. So: use one that does - fortunately, Json.NET does support this, and works fine:

string jsonData = JsonConvert.SerializeObject(pageModelInstance);

(no other changes needed, although you can safely remove the [Serializable] - that isn't needed)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top