Deserialize JSON array of arrays into List of Tuples using Newtonsoft

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

    So using JSON.NET LINQ, I managed to get it to work as you prescribed...

    var result = JsonConvert.DeserializeObject(json);
    var data = new TestData
    {
        Name = (string)result["name"],
        Data = result["data"]
            .Select(t => new Tuple(DateTime.Parse((string)t[0]), (double)t[1]))
            .ToList()
    };
    

    This is the full test I wrote

    public class TestData
    {
        public string Name;
        public List> Data;
    }
    
    [TestMethod]
    public void TestMethod1()
    {
        var json =
        @"{
            name: ""test data"",
            data: [
            [ ""2017-05-31"", 2388.33 ],
            [ ""2017-04-30"", 2358.84 ],
            [ ""2017-03-31"", 2366.82 ],
            [ ""2017-02-28"", 2329.91 ]
            ],
        }";
    
        var result = JsonConvert.DeserializeObject(json);
        var data = new TestData
        {
            Name = (string)result["name"],
            Data = result["data"]
                .Select(t => new Tuple(DateTime.Parse((string)t[0]), (double)t[1]))
                .ToList()
        };
    
        Assert.AreEqual(2388.33, data.Data[0].Item2);
    }
    

    However, while this may work, I am in agreement with the rest of the comments/answers that using tuples for this is probably not the correct way to go. Using concrete POCO's is definitely going to be a hell of a lot more maintainable in the long run simply because of the Item1 and Item2 properties of the Tuple<,>.

    They are not the most descriptive...

提交回复
热议问题