Deserialize JSON array of arrays into List of Tuples using Newtonsoft

前端 未结 4 742
半阙折子戏
半阙折子戏 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:34

    Rather than use tuples, I would create a class that is specific to the task. In this case your JSON data comes in as a list of lists of strings which is a bit awkward to deal with. One method would be to deserialise as List> and then convert afterwards. For example, I would go with 3 classes like this:

    public class IntermediateTestData
    {
        public string Name;
        public List> Data;
    }
    
    public class TestData
    {
        public string Name;
        public IEnumerable Data;
    }
    
    public class TestDataItem
    {
        public DateTime Date { get; set; }
        public double Value { get; set; }
    }
    

    Now deserialise like this:

    var intermediate = JsonConvert.DeserializeObject(json);
    
    var testData = new TestData
    {
        Name = intermediate.Name,
        Data = intermediate.Data.Select(d => new TestDataItem
        {
            Date = DateTime.Parse(d[0]),
            Value = double.Parse(d[1])
        })
    
    };
    

提交回复
热议问题