Created
August 17, 2020 09:38
-
-
Save LazyTarget/3630423c460212c12b6e619aa92a54b7 to your computer and use it in GitHub Desktop.
Json.NET deserialize generic value property as class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface IHasStringValue | |
{ | |
string Value { get; set; } | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Vehicle | |
{ | |
[JsonProperty(PropertyName = "vin")] | |
[JsonConverter(typeof(HasStringValueConverter<VinProperty>))] | |
public VinProperty Vin { get; set; } | |
[JsonProperty(PropertyName = "make")] | |
public string Make { get; set; } | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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