Created
April 14, 2022 15:53
-
-
Save chrisstraw/9b96ef5fe96ad2c36dbebb8dd31132ee to your computer and use it in GitHub Desktop.
Flatten Array to Object using Newtonsoft.Json
This file contains hidden or 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 EstimatedJurJson | |
{ | |
public int RegYear { get; set; } | |
public int Distance { get; set; } | |
} |
This file contains hidden or 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 EstimatedJurModelSerializer : JsonConverter | |
{ | |
public override bool CanConvert(Type objectType) | |
{ | |
return true; | |
} | |
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) | |
{ | |
var jsonObject = JObject.Load(reader); | |
var properties = jsonObject.Properties().ToList(); | |
return new EstimatedJurJsonModel | |
{ | |
RegYear = StringExtensions.ToInt((string) properties[0].Name, 0), | |
Distance = ((string)properties[0].Value).ToInt(0) | |
}; | |
} | |
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) | |
{ | |
var obj = value as IEnumerable<EstimatedJurJsonModel>; | |
writer.WriteStartObject(); | |
obj?.ToList().ForEach(s => | |
{ | |
writer.WritePropertyName(s.RegYear.ToString()); | |
serializer.Serialize(writer, s.Distance); | |
}); | |
writer.WriteEndObject(); | |
} | |
} |
This file contains hidden or 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 StateJson | |
{ | |
public string CountryCode { get; set; } | |
[JsonConverter(typeof(EstimatedJurModelSerializer))] | |
public IEnumerable<EstimatedJurJsonModel> EstimatedDistances { get; set; } new List<EstimatedJurJsonModel>(); | |
public bool Jurisdiction { get; set; } | |
public bool DefaultJurisdiction { get; set; } | |
public string UnitOfMeasure { get; set; } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment