I need a JsonConverter that can handle the following Json Structure. I always want back the segment model for each object in the "segments" collection in the Json. The problem I am having is how to handle the multiple structures in the Json. I am somewhat familiar with writing JsonConverters but this one has me stumped. I asked the partner we are working with if it was possible to standardize the response and was told no.
{
"segments": [
{
"headers" :
{
"agent":"000000000049",
"end_use":"consumer"
},
"data" : {
"vsd_id": "FI_444_56",
"name": "Filler Segment 4inx4inx2in",
"price":"00900",
"lead_time":"4-6"
"certificate": "BR22"
}
},
{
"vsd_id": "RB_190_01",
"name": "Rod Backer 94in",
"price":"05000",
"lead_time":"4-6"
"certificate": "BR23"
}
]
}
public class SegmentRepository {
private Newtonsoft.Json.JsonSerializer _serializer;
private HttpClient _client;
public async Task<IList<Segment>> GetSegments(....)
{
// more code here that builds the requestMessage. not important
using (var responseMessage = await _client.SendAsync(requestMessage))
using (var content = await responseMessage.Content.ReadAsStreamAsync())
using (var textReader = new StreamReader(content))
using (var reader = new JsonTextReader(textReader))
{
var response = _serializer.Deserialize<Response>(reader);
return response.Segments;
}
}
}
public class Response
{
[JsonProperty("segments")]
public List<Segment> Segments {get;set;}
}
public class Segment
{
[JsonProperty("headers")]
public Dictionary<string,string> Headers {get;set;}
[JsonProperty("data")]
public SegmentData Data {get;set;}
}
public class SegmentData
{
[JsonProperty("vsd_id")]
public string Id {get;set;}
[JsonProperty("name")]
public string Name {get;set;}
[JsonConverter(typeof(PriceConverter))]
public Decimal Price {get;set;}
[JsonProperty("lead_time")]
[JsonConverter(typeof(LeadTime))]
public LeadTime LeadTime {get;set;}
[JsonProperty("certificate")]
public string Certificate {get;set;}
}
NOTE: I have already asked the onwer of the API if they could standardize their responses and was told no.