deserialize json into list of anonymous type

2019-06-20 17:47发布

问题:

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

回答1:

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.



回答2:

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


回答3:

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