问题描述
我有一些错误的数据是从Web服务返回的,我无法更改.该服务返回一个JSON客户列表.在此列表中,每个客户还具有一个作业列表.但是返回的JSON是作业的字符串.
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.
因此:工作:"[]" ,而不是工作:[]
所以我将类定义为
[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());
没有运气.重新调整的错误是无法将System.String强制转换或转换为System.Collections.Generic.List`1 [AppNamespace.JobClass] .
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?
更新
我找到了问题,但不知道如何解决.该转换器将应用于列表内的JobClass.不去列表本身.我希望转换器仅将一次应用于列表反序列化.而是将其应用于列表中的每个JobClass记录.
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();
}
}
这篇关于正确使用Newtonsoft Json ItemConverterType的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!