Proper way of using Newtonsoft Json ItemConverterType

前端 未结 1 1990
陌清茗
陌清茗 2020-12-20 17:37

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 j

相关标签:
1条回答
  • 2020-12-20 18:23
    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();
        }
    }
    
    0 讨论(0)
提交回复
热议问题