Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify properties and field to encode and decode with Newtonsoft JSON

Tags:

json

c#

json.net

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?

like image 501
Trenskow Avatar asked Nov 29 '25 06:11

Trenskow


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"}
like image 195
Peter Csala Avatar answered Dec 01 '25 20:12

Peter Csala