【问题标题】:How to bind a JSON string to a real object definition?如何将 JSON 字符串绑定到真实对象定义?
【发布时间】:2011-12-28 18:00:06
【问题描述】:

我发现在 MVC3 中 ASP.NET 将传入的 JSON 请求正文以参数的形式映射到一个简单的指定对象非常方便...

有没有办法在特定用例之外利用此功能?

为了更进一步,在标准的 .NET 编程中获取一个 json 字符串并将其映射(绑定)到一个真实的对象...(不是字典)?

【问题讨论】:

    标签: c# asp.net json asp.net-mvc-3 serialization


    【解决方案1】:

    当然,您可以使用 JSON 序列化程序,例如 ASP.NET MVC 使用的 JavaScriptSerializer 类或第三方库,例如 Json.NET。例如:

    using System;
    using System.Web.Script.Serialization;
    
    public class Customer
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
    
    class Program
    {
        static void Main()
        {
            var serializer = new JavaScriptSerializer();
            var json = "{name: 'John', age: 15}";
            var customer = serializer.Deserialize<Customer>(json);
            Console.WriteLine("name: {0}, age: {1}", customer.Name, customer.Age);
        }
    }
    

    如果您愿意,也可以使用 Json.NET:

    using System;
    using Newtonsoft.Json;
    
    public class Customer
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
    
    class Program
    {
        static void Main()
        {
            var json = "{name: 'John', age: 15}";
            var customer = JsonConvert.DeserializeObject<Customer>(json);
            Console.WriteLine("name: {0}, age: {1}", customer.Name, customer.Age);
        }
    }
    

    【讨论】:

    • 太棒了...我看过的每个示例都使用Dictionary&lt;string, string&gt;谢谢!
    猜你喜欢
    • 2013-07-06
    • 2012-01-29
    • 1970-01-01
    • 2013-01-01
    • 1970-01-01
    • 2019-06-21
    • 1970-01-01
    • 2011-07-27
    • 2013-12-10
    相关资源
    最近更新 更多