Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

json.net

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?

like image 548
Jared Avatar asked Dec 14 '13 16:12

Jared


People also ask

Which of the following attribute should be used to indicate the property must not be serialized while using JSON serializer?

Apply a [JsonIgnore] attribute to the property that you do not want to be serialized.

What is the difference between serialize and deserialize JSON?

JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object). If you serialize this result it will generate a text with the structure and the record returned.

Which of the following attributes are required to ignore properties for JSON serializer?

To ignore individual properties, use the [JsonIgnore] attribute.

How does the Jsonproperty attribute affect JSON serialization?

JsonPropertyAttribute indicates that a property should be serialized when member serialization is set to opt-in. It includes non-public properties in serialization and deserialization. It can be used to customize type name, reference, null, and default value handling for the property value.


1 Answers

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

like image 175
Marc Gravell Avatar answered Oct 15 '22 20:10

Marc Gravell