C# 将对象编码为 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2287399/
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
Encode object to JSON
提问by Chin
Hoping I don't have to reinvent the wheel here but does anyone know if there is a class in C# similar to the one supplied by Adobe for AS3 to convert a generic object to a JSON string?
希望我不必在这里重新发明轮子,但有没有人知道 C# 中是否有一个类似于 Adobe 为 AS3 提供的类来将通用对象转换为 JSON 字符串的类?
For example, when I encode an array of objects.
例如,当我编码一个对象数组时。
new JSONEncoder(arr).getString();
Output:
输出:
[
{"type":"mobile","number":"02-8988-5566"},
{"type":"mobile","number":"02-8988-5566"}
]
采纳答案by used2could
in C#:
在 C# 中:
var jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string json = jsonSerializer.Serialize(yourCustomObject);
回答by Fredrik M?rk
The following methods work well for me (using the JavaScriptSerializer
):
以下方法对我很有效(使用JavaScriptSerializer
):
public static T FromJson<T>(string input)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Deserialize<T>(input);
}
public static string ToJson(object input)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(input);
}
回答by Rohan West
Check this out DataContractJsonSerializer.
看看这个DataContractJsonSerializer。
Use the DataContractJsonSerializer to serialize and deserialize data in the JavaScript Object Notation (JSON) format. This serialization engine converts JSON data into instances of .NET Framework types and back into JSON data
使用 DataContractJsonSerializer 以 JavaScript 对象表示法 (JSON) 格式序列化和反序列化数据。此序列化引擎将 JSON 数据转换为 .NET Framework 类型的实例,然后再转换回 JSON 数据
回答by Falanwe
I recommand using Json.NET. It's not part of .Net's the core libraries, but it is very widely used, including by a lot of Microsoft's products. Also it's the single most used nuget package. And it's both easier to use than JavaScriptSerializer
and more efficient.
我推荐使用Json.NET。它不是 .Net 核心库的一部分,但它的使用非常广泛,包括许多 Microsoft 产品。它也是最常用的nuget 包。而且它更易于使用JavaScriptSerializer
且更高效。
var jsonString = JsonConvert.SerializeObject(someObjet);
var myObject = JsonConvert.DeserializeObject<MyType>(jsonString);