Deserialize JSON array of arrays into List of Tuples using Newtonsoft

前端 未结 4 704
半阙折子戏
半阙折子戏 2021-01-05 09:48

I am receiving data that looks like this from an online service provider:

{
  name: \"test data\",
  data: [
    [ \"2017-05-31\", 2388.33 ],
    [ \"2017-04         


        
4条回答
  •  悲哀的现实
    2021-01-05 10:38

    I took the generic TupleConverter from here: Json.NET deserialization of Tuple<...> inside another type doesn't work? And made a generic TupleListConverter.

    Usage:

    public class TestData
    {
        public string Name;
        [Newtonsoft.Json.JsonConverter(typeof(TupleListConverter))]
        public List> Data;
    }
    
    public void Test(string json)
    {
        var testData = JsonConvert.DeserializeObject(json);
        foreach (var tuple in testData.data)
        {
            var dateTime = tuple.Item1;
            var price = tuple.Item2;
            ... do something...
        }
    }
    

    Converter:

    public class TupleListConverter : Newtonsoft.Json.JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return typeof(Tuple) == objectType;
        }
    
        public override object ReadJson(
            Newtonsoft.Json.JsonReader reader,
            Type objectType,
            object existingValue,
            Newtonsoft.Json.JsonSerializer serializer)
        {
            if (reader.TokenType == Newtonsoft.Json.JsonToken.Null)
                return null;
    
            var jArray = Newtonsoft.Json.Linq.JArray.Load(reader);
            var target = new List>();
    
            foreach (var childJArray in jArray.Children())
            {
                var tuple = new Tuple(
                    childJArray[0].ToObject(),
                    childJArray[1].ToObject()
                );
                target.Add(tuple);
            }
    
            return target;
        }
    
        public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
        {
            serializer.Serialize(writer, value);
        }
    }
    

提交回复
热议问题