Can I instruct Json.NET to deserialize, but not serialize, specific properties? [duplicate]

我的梦境 提交于 2020-02-19 09:50:08

问题


I have an AngularJS + MVC 5 + Web API 2 app that allows users to manage collections of objects in the browser and commit all changes at once when a Save button is clicked. As changes are made, one or more properties are added to the JavaScript objects: IsAdded, IsUpdated, IsRemoved. The properties are checked server-side to determine what to do when persisting the model.

The model is served up using Json.NET via Web API, and the base class is:

public class CollectionItemViewModel : ICollectionItem
{
    public bool IsAdded { get; set; }
    public bool IsUpdated { get; set; }
    public bool IsRemoved { get; set; }
}

This works great, but adds cruft to my serialized JSON. I can choose to not serialize these three properties with ShouldSerialize, but that also prevents them from deserializing.

public bool ShouldSerializeIsAdded()
{
    return false;
}

public bool ShouldSerializeIsUpdated()
{
    return false;
}

public bool ShouldSerializeIsRemoved()
{
    return false;
}

Is it possible to deserialize, but not serialize, specific properties using Json.NET?


回答1:


You should be able to just use the ShouldSerialize* methods as shown in the question. These only impact serialization, not deserialization.




回答2:


The correct attribute is JsonIgnore.

[JsonIgnore]
public int Id {get;set;}

Source doc available here:

http://james.newtonking.com/archive/2009/10/23/efficient-json-with-json-net-reducing-serialized-json-size



来源:https://stackoverflow.com/questions/20585810/can-i-instruct-json-net-to-deserialize-but-not-serialize-specific-properties

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!