Specify properties and field to encode and decode with Newtonsoft JSON

Viewed 155

Is it possible with Newtonsoft JSON to specify which fields should be encoded and which should be decoded?

I have an object, where all fields should be deserialized, but when serializing some fields should be ignored.

I know of JsonIgnoreAttribute, but that ignores in both directions.

Does anyone know how to achieve this?

1 Answers

You can do this by relying on the Conditional Property Serialization capability of Newtonsoft. All you need to do is to create a method named ShouldSerializeXYZ which should return a boolean. If the returned value is true then during the serialization the XYZ property will be serialized. Otherwise it will be omitted.

Sample Model class

public class CustomModel
{
    public int Id { get; set; }
    public string Description { get; set; }
    public DateTime CreatedAt { get; set; }

    public bool ShouldSerializeCreatedAt() => false;
}

Deserialization sample

var json = "{\"Id\":1,\"Description\":\"CustomModel\",\"CreatedAt\":\"2020-11-19T10:00:00Z\"}";
var model = JsonConvert.DeserializeObject<CustomModel>(json);
Console.WriteLine(model.CreatedAt); //11/19/2020 10:00:00 AM

Serialization sample

var modifiedJson = JsonConvert.SerializeObject(model);
Console.WriteLine(modifiedJson); //{"Id":1,"Description":"CustomModel"}
Related