mohsen dorparasti
mohsen dorparasti

Reputation: 8415

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

Upvotes: 7

Views: 7568

Answers (4)

Ash K
Ash K

Reputation: 3651

The below example can deserialize JSON to a list of anonymous objects using NewtonSoft.Json's DeserializeAnonymousType method.

var json = System.IO.File.ReadAllText(@"C:\TestJSONFiles\yourJSONFile.json");
var fooDefinition = new { a = "", b = 0 }; // type with fields of string, int
var fooListDefinition = Enumerable.Range(0, 0).Select(e => fooDefinition).ToList();

var foos = JsonConvert.DeserializeAnonymousType(json, fooListDefinition);

Upvotes: 0

mythz
mythz

Reputation: 143319

There are multiple ways you can dynamically parse JSON with ServiceStack's JsonSerializer e.g:

var json = "[{\"a\":\"b\",\"c\":\"d\"},{\"a\":\"e\",\"c\":\"f\"},{\"a\":\"g\",\"c\":\"h\"}]";

var dictionary = json.FromJson<List<Dictionary<string, string>>>();
".NET Collections:".Print();
dictionary.PrintDump();

List<JsonObject> map = JsonArrayObjects.Parse(json);
"Dynamically with JsonObject:".Print();
map.PrintDump();

Which uses ServiceStack's T.Dump() extension method to print out:

.NET Collections:
[
    {
        a: b,
        c: d
    },
    {
        a: e,
        c: f
    },
    {
        a: g,
        c: h
    }
]
Dynamically with JsonObject:
[
    {
        a: b,
        c: d
    },
    {
        a: e,
        c: f
    },
    {
        a: g,
        c: h
    }
]

Upvotes: 2

iamkrillin
iamkrillin

Reputation: 6876

For what you are trying to do it sounds like json.net would be a better fit. See this question Deserialize json object into dynamic object using Json.net

Upvotes: 1

Dan
Dan

Reputation: 9837

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.

Upvotes: 2

Related Questions