Proper way of using Newtonsoft Json ItemConverterType

爱⌒轻易说出口 提交于 2019-12-29 08:46:11

问题


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.


回答1:


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();
    }
}


来源:https://stackoverflow.com/questions/24639750/proper-way-of-using-newtonsoft-json-itemconvertertype

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!