3

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?

Trenskow
  • 3,783
  • 1
  • 29
  • 35
  • Maybe? https://stackoverflow.com/questions/44632448/use-different-name-for-serializing-and-deserializing-with-json-net – InUser Nov 19 '20 at 09:24

1 Answers1

4

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"}
Peter Csala
  • 17,736
  • 16
  • 35
  • 75