Skip to content

Latest commit

 

History

History
83 lines (69 loc) · 2.5 KB

CustomJsonConverter.md

File metadata and controls

83 lines (69 loc) · 2.5 KB

Custom JsonConverter

This sample creates a custom Argon.JsonConverter that overrides serialization to add a keys property.

public class KeysJsonConverter(params Type[] types) : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var token = JToken.FromObject(value);

        if (token.Type != JTokenType.Object)
        {
            token.WriteTo(writer);
        }
        else
        {
            var o = (JObject) token;
            var propertyNames = o.Properties().Select(_ => _.Name).ToList();

            o.AddFirst(new JProperty("Keys", new JArray(propertyNames)));

            o.WriteTo(writer);
        }
    }

    public override object ReadJson(JsonReader reader, Type type, object existingValue, JsonSerializer serializer) =>
        throw new NotImplementedException("Unnecessary because CanRead is false. The type will skip the converter.");

    public override bool CanRead => false;

    public override bool CanConvert(Type type) =>
        types.Any(t => t == type);
}

public class Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public IList<string> Roles { get; set; }
}

snippet source | anchor

var employee = new Employee
{
    FirstName = "James",
    LastName = "Newton-King",
    Roles = new List<string>
    {
        "Admin"
    }
};

var json = JsonConvert.SerializeObject(employee, Formatting.Indented, new KeysJsonConverter(typeof(Employee)));

Console.WriteLine(json);
// {
//   "Keys": [
//     "FirstName",
//     "LastName",
//     "Roles"
//   ],
//   "FirstName": "James",
//   "LastName": "Newton-King",
//   "Roles": [
//     "Admin"
//   ]
// }

var newEmployee = JsonConvert.DeserializeObject<Employee>(json, new KeysJsonConverter(typeof(Employee)));

Console.WriteLine(newEmployee.FirstName);
// James

snippet source | anchor