Skip to content

Instantly share code, notes, and snippets.

@chrisstraw
Created April 14, 2022 15:53
Show Gist options
  • Save chrisstraw/9b96ef5fe96ad2c36dbebb8dd31132ee to your computer and use it in GitHub Desktop.
Save chrisstraw/9b96ef5fe96ad2c36dbebb8dd31132ee to your computer and use it in GitHub Desktop.
Flatten Array to Object using Newtonsoft.Json
public class EstimatedJurJson
{
public int RegYear { get; set; }
public int Distance { get; set; }
}
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();
}
}
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