如何使用 C# 解析 JSON? [英] How can I parse JSON with C#?
问题描述
我有以下代码:
var user = (Dictionary<string, object>)serializer.DeserializeObject(responsecontent);
responsecontent
中的输入是 JSON,但没有正确解析为对象.我应该如何正确反序列化它?
The input in responsecontent
is JSON, but it is not properly parsed into an object. How should I properly deserialize it?
推荐答案
我假设你没有使用 Json.NET(Newtonsoft.Json NuGet 包).如果是这种情况,那么您应该尝试一下.
I am assuming you are not using Json.NET (Newtonsoft.Json NuGet package). If this the case, then you should try it.
它具有以下特点:
- LINQ 到 JSON
- 用于将 .NET 对象快速转换为 JSON 并再次返回的 JsonSerializer
- Json.NET 可以选择生成格式良好的缩进 JSON 以进行调试或显示
JsonIgnore
和JsonProperty
等属性可以添加到类中以自定义类的序列化方式- 能够将 JSON 与 XML 相互转换
- 支持多种平台:.NET、Silverlight 和 Compact Framework
- LINQ to JSON
- The JsonSerializer for quickly converting your .NET objects to JSON and back again
- Json.NET can optionally produce well formatted, indented JSON for debugging or display
- Attributes like
JsonIgnore
andJsonProperty
can be added to a class to customize how a class is serialized - Ability to convert JSON to and from XML
- Supports multiple platforms: .NET, Silverlight and the Compact Framework
查看下面的示例.在本例中,使用了 JsonConvert
类将对象与 JSON 相互转换.为此,它有两个静态方法.它们是 SerializeObject(Object obj)
和DeserializeObject
:
Look at the example below. In this example, JsonConvert
class is used to convert an object to and from JSON. It has two static methods for this purpose. They are SerializeObject(Object obj)
and DeserializeObject<T>(String json)
:
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
string json = JsonConvert.SerializeObject(product);
//{
// "Name": "Apple",
// "Expiry": "2008-12-28T00:00:00",
// "Price": 3.99,
// "Sizes": [
// "Small",
// "Medium",
// "Large"
// ]
//}
Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);
这篇关于如何使用 C# 解析 JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!