如何将JSON对象转换为自定义C#对象?

有一种简单的方法来填充我的C#对象与通过AJAX传递的JSON对象?

//这是使用JSON.stringify从页面传递给C#WEBMETHOD的JSON对象

{ "user" : { "name" : "asdf", "teamname" : "b", "email" : "c", "players" : ["1", "2"] } } 

// C#WebMetod接收JSON对象

 [WebMethod] public static void SaveTeam(Object user) { } 

// C#类,它表示传递给WebMethod的JSON对象的对象结构

 public class User { public string name { get; set; } public string teamname { get; set; } public string email { get; set; } public Array players { get; set; } } 

在C#中使用JSON的一个好方法是使用JSON.NET

从JSON.NET 快速启动和API文档 – 官方网站帮助您使用它。

如何使用它的一个例子:

 public class User { public User(string json) { JObject jObject = JObject.Parse(json); JToken jUser = jObject["user"]; name = (string) jUser["name"]; teamname = (string) jUser["teamname"]; email = (string) jUser["email"]; players = jUser["players"].ToArray(); } public string name { get; set; } public string teamname { get; set; } public string email { get; set; } public Array players { get; set; } } // Use private void Run() { string json = @"{""user"":{""name"":""asdf"",""teamname"":""b"",""email"":""c"",""players"":[""1"",""2""]}}"; User user = new User(json); Console.WriteLine("Name : " + user.name); Console.WriteLine("Teamname : " + user.teamname); Console.WriteLine("Email : " + user.email); Console.WriteLine("Players:"); foreach (var player in user.players) Console.WriteLine(player); } 

为了保持你的select开放,如果你使用的是.NET 3.5或更高版本,下面是一个可以直接从框架中使用generics的例子。 正如其他人所说,如果它不只是简单的对象,你应该真的使用JSON.net。

 public static string Serialize<T>(T obj) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType()); MemoryStream ms = new MemoryStream(); serializer.WriteObject(ms, obj); string retVal = Encoding.UTF8.GetString(ms.ToArray()); return retVal; } public static T Deserialize<T>(string json) { T obj = Activator.CreateInstance<T>(); MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)); DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType()); obj = (T)serializer.ReadObject(ms); ms.Close(); return obj; } 

你需要:

 using System.Runtime.Serialization; using System.Runtime.Serialization.Json; 

因为我们都爱一个内线代码

Newtonsoft比java脚本串行器更快。 …这个取决于Newtonsoft NuGet包,它比默认的序列化器更stream行,更好。

如果我们有课,然后使用下面。

 Mycustomclassname oMycustomclassname = Newtonsoft.Json.JsonConvert.DeserializeObject<Mycustomclassname>(Json Object); 

没有课,然后使用dynamic

 var oMycustomclassname = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(Json Object); 

鉴于你的代码示例,你不需要做任何事情。

如果您将该JSONstring传递给您的Web方法,它将自动分析JSONstring并创build一个填充的User对象作为您的SaveTeam方法的参数。

一般来说,你可以像下面那样使用JavascriptSerializer类,或者为了获得更多的灵活性,可以使用任何JSON框架(Jayrock JSON是一个很好的框架)来实现简单的JSON操作。

  JavaScriptSerializer jss= new JavaScriptSerializer(); User user = jss.Deserialize<User>(jsonResponse); 

下面的两个例子都使用了

  1. JavaScriptSerializerSystem.Web.Script.Serialization
  2. System.Web.Helpers下的Json.Decode

示例1:使用System.Web.Script.Serialization

 using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Web.Script.Serialization; namespace Tests { [TestClass] public class JsonTests { [TestMethod] public void Test() { var json = "{\"user\":{\"name\":\"asdf\",\"teamname\":\"b\",\"email\":\"c\",\"players\":[\"1\",\"2\"]}}"; JavaScriptSerializer serializer = new JavaScriptSerializer(); dynamic jsonObject = serializer.Deserialize<dynamic>(json); dynamic x = jsonObject["user"]; // result is Dictionary<string,object> user with fields name, teamname, email and players with their values x = jsonObject["user"]["name"]; // result is asdf x = jsonObject["user"]["players"]; // result is object[] players with its values } } } 

用法:将 JSON对象自定义为C#对象

 using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Web.Script.Serialization; using System.Linq; namespace Tests { [TestClass] public class JsonTests { [TestMethod] public void TestJavaScriptSerializer() { var json = "{\"user\":{\"name\":\"asdf\",\"teamname\":\"b\",\"email\":\"c\",\"players\":[\"1\",\"2\"]}}"; User user = new User(json); Console.WriteLine("Name : " + user.name); Console.WriteLine("Teamname : " + user.teamname); Console.WriteLine("Email : " + user.email); Console.WriteLine("Players:"); foreach (var player in user.players) Console.WriteLine(player); } } public class User { public User(string json) { JavaScriptSerializer serializer = new JavaScriptSerializer(); var jsonObject = serializer.Deserialize<dynamic>(json); name = (string)jsonObject["user"]["name"]; teamname = (string)jsonObject["user"]["teamname"]; email = (string)jsonObject["user"]["email"]; players = jsonObject["user"]["players"]; } public string name { get; set; } public string teamname { get; set; } public string email { get; set; } public Array players { get; set; } } } 

示例2:使用System.Web.Helpers

 using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Web.Helpers; namespace Tests { [TestClass] public class JsonTests { [TestMethod] public void TestJsonDecode() { var json = "{\"user\":{\"name\":\"asdf\",\"teamname\":\"b\",\"email\":\"c\",\"players\":[\"1\",\"2\"]}}"; dynamic jsonObject = Json.Decode(json); dynamic x = jsonObject.user; // result is dynamic json object user with fields name, teamname, email and players with their values x = jsonObject.user.name; // result is asdf x = jsonObject.user.players; // result is dynamic json array players with its values } } } 

用法:将 JSON对象自定义为C#对象

 using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Web.Helpers; using System.Linq; namespace Tests { [TestClass] public class JsonTests { [TestMethod] public void TestJsonDecode() { var json = "{\"user\":{\"name\":\"asdf\",\"teamname\":\"b\",\"email\":\"c\",\"players\":[\"1\",\"2\"]}}"; User user = new User(json); Console.WriteLine("Name : " + user.name); Console.WriteLine("Teamname : " + user.teamname); Console.WriteLine("Email : " + user.email); Console.WriteLine("Players:"); foreach (var player in user.players) Console.WriteLine(player); } } public class User { public User(string json) { var jsonObject = Json.Decode(json); name = (string)jsonObject.user.name; teamname = (string)jsonObject.user.teamname; email = (string)jsonObject.user.email; players = (DynamicJsonArray) jsonObject.user.players; } public string name { get; set; } public string teamname { get; set; } public string email { get; set; } public Array players { get; set; } } } 

这段代码需要添加System.Web.Helpers中find的命名空间,

%ProgramFiles%\ Microsoft ASP.NET \ ASP.NET网页{VERSION} \ Assemblies \ System.Web.Helpers.dll

要么

%ProgramFiles(x86)%\ Microsoft ASP.NET \ ASP.NET网页{VERSION} \ Assemblies \ System.Web.Helpers.dll

希望这可以帮助!

另一个非常简单的解决scheme是使用库Newtonsoft.Json:

 User user = JsonConvert.DeserializeObject<User>(jsonString); 

这是一个非常方便的工具,可以从JSON创buildC#对象模型*: http : //json2csharp.com

使用JavaScriptSerializer()并不比提供的通用解决scheme严格:public static T Deserialize(string json)

当将json传递到与您要转换的对象定义完全不匹配的服务器时,这可能会很方便。

 public static class Utilities { public static T Deserialize<T>(string jsonString) { using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString))) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T)); return (T)serializer.ReadObject(ms); } } } 

更多信息转到以下链接http://ishareidea.blogspot.in/2012/05/json-conversion.html

关于DataContractJsonSerializer Class你可以在这里阅读。

在性能方面,我发现ServiceStack的串行器比其他的要快一些。 它是ServiceStack.Text命名空间中的JsonSerializer类。

https://github.com/ServiceStack/ServiceStack.Text

ServiceStack通过NuGet包可用: https : //www.nuget.org/packages/ServiceStack/

JSON.Net是最好的select,但根据对象的形状以及是否存在循环依赖关系,可以使用JavaScriptSerializer或DataContractSerializer。

codeplex上的JSON C#类生成器生成与NewtonSoftJS很好地协作的类。

JavaScript序列化程序:需要using System.Web.Script.Serialization;

 public class JavaScriptSerializerDeSerializer<T> { private readonly JavaScriptSerializer serializer; public JavaScriptSerializerDeSerializer() { this.serializer = new JavaScriptSerializer(); } public string Serialize(T t) { return this.serializer.Serialize(t); } public T Deseralize(string stringObject) { return this.serializer.Deserialize<T>(stringObject); } } 

数据合同序列化程序:需要using System.Runtime.Serialization.Json; – 通用typesT应该在数据合同上更多地序列化

 public class JsonSerializerDeserializer<T> where T : class { private readonly DataContractJsonSerializer jsonSerializer; public JsonSerializerDeserializer() { this.jsonSerializer = new DataContractJsonSerializer(typeof(T)); } public string Serialize(T t) { using (var memoryStream = new MemoryStream()) { this.jsonSerializer.WriteObject(memoryStream, t); memoryStream.Position = 0; using (var sr = new StreamReader(memoryStream)) { return sr.ReadToEnd(); } } } public T Deserialize(string objectString) { using (var ms = new MemoryStream(System.Text.ASCIIEncoding.ASCII.GetBytes((objectString)))) { return (T)this.jsonSerializer.ReadObject(ms); } } } 

此网站也可以帮助您从JSONinput生成类。 生成JSON到CSHARP CLASSES GENERATOR类非常出色

而不是只发送一个对象。

创build一个可访问的属性的公共类,并将数据发送到Webmethod。

 [WebMethod] public static void SaveTeam(useSomeClassHere user) { } 

在ajax调用中使用相同的参数名称来发送数据。