Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

deserialize json into list of anonymous type

I have a json as below :

  "[{"a":"b","c":"d"},{"a":"e","c":"f"},{"a":"g","c":"h"}]"

now I want to deserilize this into a list of objects of anonymous type "foo"

  var foo=new { a=string.empty , c=string.empty };

the code is :

  ServiceStackJsonSerializer Jserializer = new ServiceStackJsonSerializer();
  dynamic foos = Jserializer.Deserialize<List<foo.GetType()>>(jsonString);

but not working .

update :

replacing ServiceStack with JavascriptSerializer and passing dictionary[] solved the problem without need to anonymous Type

        JavaScriptSerializer jSerializer = new JavaScriptSerializer();
        var Foos = jSerializer.Deserialize<Dictionary<string, object>[]>(jsonString);
like image 832
mohsen dorparasti Avatar asked Aug 08 '12 18:08

mohsen dorparasti


1 Answers

I don't know what the Jserializer class is, but I do know of the JavaScriptSerializer class. Unfortunately, it doesn't support deserialization into anonymous types. You'll have to create a concrete type like this:

class Foo
{
    public string a { get; set; }

    public string c { get; set; }
}

Using the following code worked for me:

const string json =
    @"[{""a"":""b"",""c"":""d""},{""a"":""e"",""c"":""f""},{""a"":""g"",""c"":""h""}]";

var foos = new JavaScriptSerializer().Deserialize<Foo[]>(json);

the variable foos will contain an array of Foo instances.

like image 129
Dan Avatar answered Sep 20 '22 13:09

Dan