I have some bad data coming back from a web service which I cannot change. The service returns a JSON list of customers. Inside this list, each customer also has a list of jobs. But the JSON coming back is a string for the jobs.
So: Jobs: "[]" Instead of Jobs: []
So I defined the class as
[JsonProperty(PropertyName = "JOBS", ItemConverterType = typeof(StringToJobsConverter))]
public List<JobClass> Jobs { get; set; }
I created the class, and created the conversion method inside it as follows:
return JsonConvert.DeserializeObject<List<JobClass>>(existingValue.ToString());
No luck. The error retuned is Could not cast or convert from System.String to System.Collections.Generic.List`1[AppNamespace.JobClass].
Breakpoints in the converter code are never hit. Can anyone see what I'm doing wrong?
UPDATE
I found the issue but don't know how to fix. The converter is being applied to the JobClass inside the list. Not to the List itself. I want the converter applied one time only to the List deserialization. Instead it's applied to each JobClass record inside the list.
string json = @"{str1:""abc"",list:""[1,2,3]"", str2:""def""}";
var temp = JsonConvert.DeserializeObject<Temp>(json);
public class Temp
{
public string str1;
[JsonConverter(typeof(StringConverter<List<int>>))]
public List<int> list;
public string str2;
}
public class StringConverter<T> : JsonConverter
{
public override bool CanConvert(Type objectType)
{
throw new NotImplementedException();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return JsonConvert.DeserializeObject<T>((string)reader.Value);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With