12

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?

Jared
  • 1,385
  • 11
  • 21
  • 3
    ShouldSerialize* absolutely should not impact deserialization. Are you absolutely sure about that? Because that would be a major bug – Marc Gravell Dec 14 '13 at 17:23

2 Answers2

16

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

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • Thanks for the reality check. I swear I tested this as described in my comment on Softlion's answer, but apparently not closely enough. Deserialization is working as expected; the problem was unrelated and specific to my app. – Jared Dec 14 '13 at 19:15
-7

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

Softlion
  • 12,281
  • 11
  • 58
  • 88
  • 2
    As far as I can tell, JsonIgnore prevents deserialization, too. I tested by using Fiddler to capture a sample POST where IsAdded = true, then replayed that same POST both with and without JsonIgnore on my IsAdded property. As Marc asserted, it correctly deserialized to true with ShouldSerializeIsAdded returning false and without JsonIgnore. Adding JsonIgnore caused IsAdded = false. – Jared Dec 14 '13 at 19:12
  • 2
    @Jared indeed, this will make the property completely unused - it won't be used during deserialization either. – Marc Gravell Dec 14 '13 at 19:20