Skip to content

Latest commit

 

History

History
54 lines (44 loc) · 1.74 KB

JsonConverterAttributeClass.md

File metadata and controls

54 lines (44 loc) · 1.74 KB

JsonConverterAttribute on a class

This sample uses the Argon.JsonConverterAttribute to specify that a Argon.JsonConverter should be used when serializing and deserializing a class.

public class UserConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var user = (User) value;

        writer.WriteValue(user.UserName);
    }

    public override object ReadJson(JsonReader reader, Type type, object existingValue, JsonSerializer serializer)
    {
        var user = new User
        {
            UserName = (string) reader.Value
        };

        return user;
    }

    public override bool CanConvert(Type type) =>
        type == typeof(User);
}

[JsonConverter(typeof(UserConverter))]
public class User
{
    public string UserName { get; set; }
}

snippet source | anchor

var user = new User
{
    UserName = @"domain\username"
};

var json = JsonConvert.SerializeObject(user, Formatting.Indented);

Console.WriteLine(json);
// "domain\\username"

snippet source | anchor