Skip to content

Instantly share code, notes, and snippets.

@LazyTarget
Created August 17, 2020 09:38
Show Gist options
  • Save LazyTarget/3630423c460212c12b6e619aa92a54b7 to your computer and use it in GitHub Desktop.
Save LazyTarget/3630423c460212c12b6e619aa92a54b7 to your computer and use it in GitHub Desktop.
Json.NET deserialize generic value property as class
public class HasStringValueConverter<TObject> : JsonConverter<TObject>
where TObject : IHasStringValue, new()
{
public override bool CanRead { get; } = true;
public override bool CanWrite { get; } = true;
public override void WriteJson(JsonWriter writer, TObject value, JsonSerializer serializer)
{
writer.WriteValue(value?.Value);
}
public override TObject ReadJson(JsonReader reader, Type objectType, TObject existingValue, bool hasExistingValue, JsonSerializer serializer)
{
if (hasExistingValue)
{
return existingValue;
}
else
{
var str = reader.Value?.ToString();
var prop = new TObject { Value = str };
return prop;
}
}
}
public interface IHasStringValue
{
string Value { get; set; }
}
public class Vehicle
{
[JsonProperty(PropertyName = "vin")]
[JsonConverter(typeof(HasStringValueConverter<VinProperty>))]
public VinProperty Vin { get; set; }
[JsonProperty(PropertyName = "make")]
public string Make { get; set; }
}
[DataContract]
public class VinProperty : IHasStringValue
{
/// <summary>
/// Vehicle Identification Number
/// </summary>
[JsonProperty(PropertyName = "value")]
public string Value { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment