如何将 JSON 对象转换为自定义 C# 对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2246694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Convert JSON object to Custom C# object?
提问by MHop
Is there an easy way to populate my C# Object with the JSON object passed via AJAX?
有没有一种简单的方法可以用通过 AJAX 传递的 JSON 对象填充我的 C# 对象?
This is the JSON Object passed to C# WEBMETHOD from the page using JSON.stringify
这是使用 JSON.stringify 从页面传递给 C# WEBMETHOD 的 JSON 对象
{
"user": {
"name": "asdf",
"teamname": "b",
"email": "c",
"players": ["1", "2"]
}
}
C# WebMetod That receives the JSON Object
接收 JSON 对象的 C# WebMetod
[WebMethod]
public static void SaveTeam(Object user)
{
}
C# Class that represents the object structure of JSON Object passed in to the WebMethod
C# 类,表示传入 WebMethod 的 JSON Object 的对象结构
public class User
{
public string name { get; set; }
public string teamname { get; set; }
public string email { get; set; }
public Array players { get; set; }
}
采纳答案by AndreyAkinshin
A good way to use JSON in C# is with JSON.NET
在 C# 中使用 JSON 的一个好方法是使用JSON.NET
Quick Starts & API Documentationfrom JSON.NET - Official sitehelp you work with it.
来自 JSON.NET 的快速入门和 API 文档- 官方网站可帮助您使用它。
An example of how to use it:
如何使用它的示例:
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);
}
回答by womp
Given your code sample, you shouldn't need to do anything else.
鉴于您的代码示例,您应该不需要做任何其他事情。
If you pass that JSON string to your web method, it will automatically parse the JSON string and create a populated User object as the parameter for your SaveTeam method.
如果您将该 JSON 字符串传递给您的 Web 方法,它将自动解析 JSON 字符串并创建一个填充的 User 对象作为您的 SaveTeam 方法的参数。
Generally though, you can use the JavascriptSerializer
class as below, or for more flexibility, use any of the various Json frameworks out there (Jayrock JSON is a good one) for easy JSON manipulation.
不过,一般来说,您可以使用JavascriptSerializer
下面的类,或者为了更大的灵活性,使用各种 Json 框架中的任何一个(Jayrock JSON 是一个很好的框架)以便于 JSON 操作。
JavaScriptSerializer jss= new JavaScriptSerializer();
User user = jss.Deserialize<User>(jsonResponse);
回答by Sky Sanders
JSON.Net is your best bet but, depending on the shape of the objects and whether there are circular dependencies, you could use JavaScriptSerializer or DataContractSerializer.
JSON.Net 是您最好的选择,但是,根据对象的形状以及是否存在循环依赖,您可以使用 JavaScriptSerializer 或 DataContractSerializer。
回答by Jammin
To keep your options open, if you're using .NET 3.5 or later, here is a wrapped up example you can use straight from the framework using Generics. As others have mentioned, if it's not just simple objects you should really use JSON.net.
为了让您的选择保持开放,如果您使用 .NET 3.5 或更高版本,这里有一个完整的示例,您可以使用泛型直接从框架中使用。正如其他人所提到的,如果它不仅仅是简单的对象,您应该真正使用 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;
}
You'll need:
你需要:
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
回答by Ioannis Suarez
Using JavaScriptSerializer() is less strict than the generic solution offered : public static T Deserialize(string json)
使用 JavaScriptSerializer() 不如提供的通用解决方案严格:public static T Deserialize(string json)
That might come handy when passing json to the server that does not match exactly the Object definition you are trying to convert to.
当将 json 传递到与您尝试转换为的对象定义不完全匹配的服务器时,这可能会派上用场。
回答by Syam Developer
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);
}
}
}
More information go to following link http://ishareidea.blogspot.in/2012/05/json-conversion.html
更多信息请访问以下链接 http://ishareidea.blogspot.in/2012/05/json-conversion.html
About DataContractJsonSerializer Class
you can read here.
关于DataContractJsonSerializer Class
你可以在这里阅读。
回答by ΩmegaMan
The JSON C# class generator on codeplexgenerates classes which work well with NewtonSoftJS.
Codeplex上的JSON C# 类生成器生成与 NewtonSoftJS 配合良好的类。
回答by ΩmegaMan
The following 2 examples make use of either
以下 2 个示例使用了
- JavaScriptSerializerunder System.Web.Script.SerializationOr
- Json.Decodeunder System.Web.Helpers
- System.Web.Script.Serialization下的JavaScriptSerializer或
- System.Web.Helpers下的Json.Decode
Example 1:using System.Web.Script.Serialization
示例 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
}
}
}
Usage:JSON object to Custom C# object
用法: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; }
}
}
Example 2:using System.Web.Helpers
示例 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
}
}
}
Usage:JSON object to Custom C# object
用法: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; }
}
}
This code requires adding System.Web.Helpers namespace found in,
此代码需要添加 System.Web.Helpers 命名空间,
%ProgramFiles%\Microsoft ASP.NET\ASP.NET Web Pages{VERSION}\Assemblies\System.Web.Helpers.dll
%ProgramFiles%\Microsoft ASP.NET\ASP.NET 网页{版本}\Assemblies\System.Web.Helpers.dll
Or
或者
%ProgramFiles(x86)%\Microsoft ASP.NET\ASP.NET Web Pages{VERSION}\Assemblies\System.Web.Helpers.dll
%ProgramFiles(x86)%\Microsoft ASP.NET\ASP.NET 网页{版本}\Assemblies\System.Web.Helpers.dll
Hope this helps!
希望这可以帮助!
回答by MSTdev
Since we all love one liners code
因为我们都喜欢一个班轮代码
Newtonsoft is faster than java script serializer. ... this one depends on the Newtonsoft NuGet package, which is popular and better than the default serializer.
Newtonsoft 比 java 脚本序列化器快。...这个依赖于 Newtonsoft NuGet 包,它很流行并且比默认的序列化器更好。
if we have class then use below.
如果我们有课程,请在下面使用。
Mycustomclassname oMycustomclassname = Newtonsoft.Json.JsonConvert.DeserializeObject<Mycustomclassname>(jsonString);
no class then use dynamic
没有类然后使用动态
var oMycustomclassname = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(jsonString);
回答by BTE
JavaScript Serializer: requires using System.Web.Script.Serialization;
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);
}
}
Data Contract Serializer: requires using System.Runtime.Serialization.Json;
- The generic type T should be serializable more on Data Contract
数据契约序列化程序:需要using System.Runtime.Serialization.Json;
- 泛型类型 T 应该在数据契约上更多地可序列化
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);
}
}
}