deserialize json into list of anonymous type

柔情痞子 提交于 2019-12-08 20:13:42

问题


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



来源:https://stackoverflow.com/questions/11870906/deserialize-json-into-list-of-anonymous-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!