Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将JSON字符串绑定到真实的对象定义?_C#_Asp.net_Json_Asp.net Mvc 3_Serialization - Fatal编程技术网

C# 如何将JSON字符串绑定到真实的对象定义?

C# 如何将JSON字符串绑定到真实的对象定义?,c#,asp.net,json,asp.net-mvc-3,serialization,C#,Asp.net,Json,Asp.net Mvc 3,Serialization,我发现在MVC3中,ASP.NET将传入的JSON请求体以参数的形式映射到一个简单的指定对象非常方便 是否有任何方法可以在特定用例之外利用此功能 更进一步说,在标准的.NET编程中,获取一个json字符串并将其映射(绑定)到一个真实的对象。。。(不是字典)?当然,您可以使用JSON序列化程序,如ASP.NET MVC使用的类或第三方库,如。例如: using System; using System.Web.Script.Serialization; public class Customer

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

是否有任何方法可以在特定用例之外利用此功能


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

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

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);
    }
}
使用系统;
使用System.Web.Script.Serialization;
公共类客户
{
公共字符串名称{get;set;}
公共整数{get;set;}
}
班级计划
{
静态void Main()
{
var serializer=新的JavaScriptSerializer();
var json=“{name:'John',年龄:15}”;
var customer=serializer.Deserialize(json);
WriteLine(“名称:{0},年龄:{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);
    }
}
使用系统;
使用Newtonsoft.Json;
公共类客户
{
公共字符串名称{get;set;}
公共整数{get;set;}
}
班级计划
{
静态void Main()
{
var json=“{name:'John',年龄:15}”;
var customer=JsonConvert.DeserializeObject(json);
WriteLine(“名称:{0},年龄:{1}”,customer.name,customer.age);
}
}

太棒了。。。我看过的每个例子都使用了
字典
谢谢!