反序列化json

时间:2011-11-28 08:20:23

标签: asp.net json c#-4.0

如何将以下JSON字符串反序列化为对象?

{
    "ArrayOfResults": {
        "Results": [
            {
                "ErrorID": "0",
                "ErrorMessage": null,
                "MetroID": "281",
                "MetroName": "050908 add metor no dffd"
            },
            {
                "ErrorID": "0",
                "ErrorMessage": null,
                "MetroID": "284",
                "MetroName": "050908 added with dff"
            }
        ]
    }
}

3 个答案:

答案 0 :(得分:0)

您可以使用此框架:http://json.codeplex.com/

取自documentation

JObject o = new JObject(
  new JProperty("Name", "John Smith"),
  new JProperty("BirthDate", new DateTime(1983, 3, 20))
  );

JsonSerializer serializer = new JsonSerializer();
Person p = (Person)serializer.Deserialize(new JTokenReader(o), typeof(Person));

Console.WriteLine(p.Name);
// John Smith

答案 1 :(得分:0)

您展示的是无效的JSON 。您需要修复JSON以便希望使用JSON序列化程序来处理它:

{
    "ArrayOfResults": {
        "Results": [
            {
                "ErrorID": "0",
                "ErrorMessage": null,
                "MetroID": "281",
                "MetroName": "050908 add metor no dffd"
            },
            {
                "ErrorID": "0",
                "ErrorMessage": null,
                "MetroID": "284",
                "MetroName": "050908 added with dff"
            }
        ]
    }
}

修复后,可以使用JavaScriptSerializer类将其反序列化为您定义的强类型模型:

public class Item
{
    public int ErrorID { get; set; }
    public string ErrorMessage { get; set; }
    public int MetroID { get; set; }
    public string MetroName { get; set; }
}

public class ResultArray
{
    public Item[] Results { get; set; }
}

public class Result
{
    public ResultArray ArrayOfResults { get; set; }
}

class Program
{
    static void Main()
    {
        var json = @"{ ""ArrayOfResults"": { ""Results"": [ {""ErrorID"": ""0"", ""ErrorMessage"": null, ""MetroID"": ""281"", ""MetroName"": ""050908 add metor no dffd"" }, {""ErrorID"": ""0"", ""ErrorMessage"": null, ""MetroID"": ""284"", ""MetroName"": ""050908 added with dff"" }]}}";
        var serializer = new JavaScriptSerializer();
        var response = serializer.Deserialize<Result>(json);

        // TODO: do something with the response
    }
}

答案 2 :(得分:0)

var s = new JavaScriptSerializer();
var result = s.Deserialize<List<YourType>>(strJson);

当然,以类似方式序列化类型列表会更好