Arnab Arnab - 1 month ago 8
C# Question

Deserialize json string to C# anonymous array

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);


What I wish to do is deserialize jsondata to same object as in data1 (C# array with anonymous type{string Product, int Year, int Sales})

I tried without success..

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


How do I know.. Because the following does not work though it works with the original C# array(data1)

foreach (var d in data)
{
int a = d.Year;
}


Without creating a separate class, can I do this..

Answer

There are trick, howto deserialize it without dynamics. It should be a liiiiitle bit faster. This also can be as generic solution

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;
        }
    }
}

So, usage:

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);
}