Trenskow
Trenskow

Reputation: 3793

Specify properties and field to encode and decode with Newtonsoft JSON

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?

Upvotes: 3

Views: 588

Answers (1)

Peter Csala
Peter Csala

Reputation: 22829

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"}

Upvotes: 4

Related Questions