将json字符串反序列化为c#匿名数组

本文关键字:数组 json 字符串 反序列化 | 更新日期: 2023-09-27 18:13:55

var data1 = new[] { 
              new { Product = "Product 1", Year = 2009, Sales = 1212 },
              new { Product = "Product 2", Year = 2009, Sales = 522 },
              new { Product = "Product 1", Year = 2010, Sales = 1337 },
              new { Product = "Product 2", Year = 2011, Sales = 711 },
              new { Product = "Product 2", Year = 2012, Sales = 2245 },
              new { Product = "Product 3", Year = 2012, Sales = 1000 }
          };
            string jsondata =JsonConvert.SerializeObject(data1);

我想做的是将jsondata反序列化为与data1相同的对象(c#数组具有匿名类型{string Product, int Year, int Sales})

I tried without success.

var dataj = JsonConvert.DeserializeObject<JArray>(jsondata);
            var data = dataj.ToArray();

我怎么知道…因为下面的代码不能工作,尽管它可以与原始c#数组(data1)

一起工作
foreach (var d in data)
            {
                int a = d.Year;
            }

将json字符串反序列化为c#匿名数组

您需要使用dynamic关键字,因为Year不是JToken的真正属性。运行时绑定器可以通过内省JToken来检索该值。

这是你唯一需要修改的行:

dynamic data = dataj.ToArray();

在你的原始代码中,类型是匿名的,但这并不意味着它不能知道它有什么属性

在没有动态的情况下如何反序列化是有技巧的。它应该稍微快一点。这也可以作为通用解决方案

public static class Ext
{
    public static IEnumerable<T> Deserialize<T>(this string source, T typeHolder)
    {
        var ltype = typeof(List<>);
        var constructed = ltype.MakeGenericType(new[] { typeHolder.GetType() });
        // deserializing
        return (JsonConvert.DeserializeObject(source, constructed) as IList).Cast(typeHolder);
    }
    public static IEnumerable<T> Cast<T>(this IEnumerable x, T typeHolder)
    {
        foreach (var item in x)
        {
            yield return (T)item;
        }
    }
}

所以,用法:

void Main()
{
    var data1 = new[] {
                      new { Product = "Product 1", Year = 2009, Sales = 1212 },
                      new { Product = "Product 2", Year = 2009, Sales = 522 },
                      new { Product = "Product 1", Year = 2010, Sales = 1337 },
                      new { Product = "Product 2", Year = 2011, Sales = 711 },
                      new { Product = "Product 2", Year = 2012, Sales = 2245 },
                      new { Product = "Product 3", Year = 2012, Sales = 1000 }
                  };
    string jsondata = JsonConvert.SerializeObject(data1);
    var ob = new { Product = "Product 1", Year = 2009, Sales = 1212 };
    var deserializedObject = jsondata.Deserialize(ob);
}