Reputation: 3793
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
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.
public class CustomModel
{
public int Id { get; set; }
public string Description { get; set; }
public DateTime CreatedAt { get; set; }
public bool ShouldSerializeCreatedAt() => false;
}
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
var modifiedJson = JsonConvert.SerializeObject(model);
Console.WriteLine(modifiedJson); //{"Id":1,"Description":"CustomModel"}
Upvotes: 4