如何使用 C# 解析 JSON? [英] How can I parse JSON with C#?

查看:27
本文介绍了如何使用 C# 解析 JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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.

它具有以下特点:

  1. LINQ 到 JSON
  2. 用于将 .NET 对象快速转换为 JSON 并再次返回的 JsonSerializer
  3. Json.NET 可以选择生成格式良好的缩进 JSON 以进行调试或显示
  4. JsonIgnoreJsonProperty 等属性可以添加到类中以自定义类的序列化方式
  5. 能够将 JSON 与 XML 相互转换
  6. 支持多种平台:.NET、Silverlight 和 Compact Framework
  1. LINQ to JSON
  2. The JsonSerializer for quickly converting your .NET objects to JSON and back again
  3. Json.NET can optionally produce well formatted, indented JSON for debugging or display
  4. Attributes like JsonIgnore and JsonProperty can be added to a class to customize how a class is serialized
  5. Ability to convert JSON to and from XML
  6. Supports multiple platforms: .NET, Silverlight and the Compact Framework

查看下面的示例.在本例中,使用了 JsonConvert 类将对象与 JSON 相互转换.为此,它有两个静态方法.它们是 SerializeObject(Object obj)DeserializeObject(String json):

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆