如何用C#解析JSON?

424 c# json json.net deserialization

我有以下代码:

var user = (Dictionary<string, object>)serializer.DeserializeObject(responsecontent);
Run Code Online (Sandbox Code Playgroud)

输入responsecontent是JSON,但未正确解析为对象.我应该如何正确地反序列化它?

MD *_*med 350

我假设你没有使用Json.NET(Newtonsoft.Json NuGet包).如果是这种情况,那么你应该尝试一下.

它具有以下功能:

  1. LINQ to JSON
  2. JsonSerializer用于快速将.NET对象转换为JSON并再次返回
  3. Json.NET可以选择生成格式良好的缩进JSON,用于调试或显示
  4. 可以将类似JsonIgnore和JsonProperty的属性添加到类中以自定义类的序列化方式
  5. 能够将JSON转换为XML和从XML转换
  6. 支持多种平台:.NET,Silverlight和Compact Framework

看下面的例子.在此示例中,JsonConvert类用于将对象转换为JSON和从JSON转换对象.它有两种静态方法用于此目的.他们是SerializeObject(Object obj)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);
Run Code Online (Sandbox Code Playgroud)

  • 为什么每个人都有这样的问题,在他们的答案中包含相关的`require`,`include`,`import`或`using`语句.那一行会受伤吗? (29认同)
  • 我可以反序列化为``var``类型变量,在我不知道我的目标的完整结构的情况下?具体来说,我正在使用Rally用户故事,我想将它们转换为对象. (15认同)
  • @VANDERWEYENJonathan - 在现代Web浏览器中,JSON.parse(字符串)和JSON.stringify(对象)都将日期作为ISO8601字符串处理,这是上面答案中描述的格式.您可能希望在人们认为标准不相关之前更新您的标准.人们需要的日期远远超过他们的标准. (15认同)
  • @PeterWone:不,`JSON.parse('{"Expiry":"2008-12-28T00:00:00"}').Expiry`返回**字符串**`"2008-12-28T00:00: 00"`,而不是约会.它可以通过`new Date(str)`转换为*Date`,但是`JSON.parse`对日期一无所知.你必须传递一个reviver,它根据模式检查每个字符串值. (3认同)
  • 由于3.703秒与3s和703ms相同而且分隔符是小数点,我告诉你这是几秒到三位小数. (3认同)

Dmi*_*lov 263

正如这里所回答的那样 - 将JSON反序列化为C#动态对象?

使用Json.NET非常简单:

dynamic stuff = JsonConvert.DeserializeObject("{ 'Name': 'Jon Smith', 'Address': { 'City': 'New York', 'State': 'NY' }, 'Age': 42 }");

string name = stuff.Name;
string address = stuff.Address.City;
Run Code Online (Sandbox Code Playgroud)

或者使用Newtonsoft.Json.Linq:

dynamic stuff = JObject.Parse("{ 'Name': 'Jon Smith', 'Address': { 'City': 'New York', 'State': 'NY' }, 'Age': 42 }");

string name = stuff.Name;
string address = stuff.Address.City;
Run Code Online (Sandbox Code Playgroud)

  • @MaxHodges,你是对的.我只是使用内联"魔术字符串"来演示如何解析JSON字符串值.不希望它看起来复杂与转义双引号.在实际代码中,我们通常将JSON字符串作为变量从某处获得或作为参数传递. (13认同)
  • 如果没有.net 4,您就没有'dynamic'关键字.您可以使用'var stuff'进行声明,而不是'stuff.Name'和'stuff.Address.City',你有'stuff ["Name"]'和'stuff ["Address"] ["City"]' . (4认同)
  • @Fil 这给了你一个 `object` 类型的值,你不能在 `object` 上使用索引。 (3认同)

qqb*_*enq 128

以下是一些使用第三方库的选项:

// For that you will need to add reference to System.Runtime.Serialization
var jsonReader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(@"{ ""Name"": ""Jon Smith"", ""Address"": { ""City"": ""New York"", ""State"": ""NY"" }, ""Age"": 42 }"), new System.Xml.XmlDictionaryReaderQuotas());

// For that you will need to add reference to System.Xml and System.Xml.Linq
var root = XElement.Load(jsonReader);
Console.WriteLine(root.XPathSelectElement("//Name").Value);
Console.WriteLine(root.XPathSelectElement("//Address/State").Value);

// For that you will need to add reference to System.Web.Helpers
dynamic json = System.Web.Helpers.Json.Decode(@"{ ""Name"": ""Jon Smith"", ""Address"": { ""City"": ""New York"", ""State"": ""NY"" }, ""Age"": 42 }");
Console.WriteLine(json.Name);
Console.WriteLine(json.Address.State);
Run Code Online (Sandbox Code Playgroud)

有关System.Web.Helpers.Json的更多信息,请参阅该链接.

更新:现在最简单的方法Web.Helpers是使用NuGet包.


如果您不关心早期的Windows版本,可以使用Windows.Data.Json命名空间的类:

// minimum supported version: Win 8
JsonObject root = Windows.Data.Json.JsonValue.Parse(jsonString).GetObject();
Console.WriteLine(root["Name"].GetString());
Console.WriteLine(root["Address"].GetObject()["State"].GetString());
Run Code Online (Sandbox Code Playgroud)

  • Json.Net不再是第三方组件了.[微软最近自己使用它.它是Web API上的默认serilizer.](http://stackoverflow.com/a/13491818/542251) (3认同)
  • 我使用了这里描述的Web.Helpers方法,但遇到了这篇文章解决的问题:http://stackoverflow.com/questions/7066726/attempt-by-method-system-web-helpers-json-cctor-to -access法系统,我们 (2认同)

Elo*_*dev 60

如果您可以使用.NET 4,请查看:http://visitmix.com/writings/the-rise-of-json(archive.org)

以下是该网站的摘录:

WebClient webClient = new WebClient();
dynamic result = JsonValue.Parse(webClient.DownloadString("https://api.foursquare.com/v2/users/self?oauth_token=XXXXXXX"));
Console.WriteLine(result.response.user.firstName);
Run Code Online (Sandbox Code Playgroud)

最后一个Console.WriteLine很可爱......

  • 期待您找到这个图书馆.编辑:是这个:http://dynamicjson.codeplex.com/? (7认同)

fr3*_*535 32

另一个本机解决方案是JavaScriptSerializer ,它不需要任何第三方库,而是对System.Web.Extensions的引用.从3.5开始,这不是一个新的但是非常未知的内置功能.

using System.Web.Script.Serialization;
Run Code Online (Sandbox Code Playgroud)

..

JavaScriptSerializer serializer = new JavaScriptSerializer();
objectString = serializer.Serialize(new MyObject());
Run Code Online (Sandbox Code Playgroud)

然后回来

MyObject o = serializer.Deserialize<MyObject>(objectString)
Run Code Online (Sandbox Code Playgroud)

  • @ fr34kyn01535:Windows XP在桌面上占据第二大市场份额.这是相关的. (3认同)
  • 这非常好,但它需要Web组件,所以不幸的是它在.NET 4.0 Client Profile中不起作用,这是Windows XP的最后一个.NET版本.可以完全安装.NET,但很多人只使用Client Profile.相反,即使在客户端配置文件中也支持System.Runtime.Serialization.Json.DataContractJsonSerializer. (2认同)

hal*_*ldo 21

系统.Text.Json

.NET core 3.0System.Text.Json内置了这意味着您可以在使用第三方库的情况下反序列化/序列化 JSON 。

将您的类序列化为 JSON 字符串:

var json = JsonSerializer.Serialize(order);
Run Code Online (Sandbox Code Playgroud)

要将 JSON 反序列化为强类型类:

var order = JsonSerializer.Deserialize<Order>(json);
Run Code Online (Sandbox Code Playgroud)

所以如果你有一个像下面这样的类:

public class Order
{
    public int Id { get; set; }
    public string OrderNumber { get; set; }
    public decimal Balance { get; set; }
    public DateTime Opened { get; set; }
}

var json = JsonSerializer.Serialize(order);
// creates JSON ==>
{
    "id": 123456,
    "orderNumber": "ABC-123-456",
    "balance": 9876.54,
    "opened": "2019-10-21T23:47:16.85",
};

var order = JsonSerializer.Deserialize<Order>(json);
// ==> creates the above class
Run Code Online (Sandbox Code Playgroud)

需要注意的一件事是,在使用您自己的代码时System.Text.Json 不会自动处理camelCaseJSON 属性(但是,在使用 MVC/WebAPI 请求和模型绑定器时会这样做)。

要解决此问题,您需要将其JsonSerializerOptions作为参数传递。

JsonSerializerOptions options = new JsonSerializerOptions
{        
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,  // set camelCase       
    WriteIndented = true                                // write pretty json
};

// pass options to serializer
var json = JsonSerializer.Serialize(order, options);
// pass options to deserializer
var order = JsonSerializer.Deserialize<Order>(json, options);
Run Code Online (Sandbox Code Playgroud)

System.Text.Json也可用于 .Net Framework 和 .Net Standard 作为 Nu-get 包System.Text.Json

  • @Cherona 使用 `JsonDocument.Parse`。 (5认同)
  • 如果没有课怎么办?如果您只是模糊地知道 json 数据将包含什么内容怎么办?或者钥匙是否存在? (3认同)
  • 在 .NET 6 中 `JsonNode.Parse()` 提供了解析“未知”json 的功能 (3认同)

Zun*_*air 13

System.Json现在可以工作...

安装nuget https://www.nuget.org/packages/System.Json

PM> Install-Package System.Json -Version 4.5.0
Run Code Online (Sandbox Code Playgroud)

样品

// PM>Install-Package System.Json -Version 4.5.0

using System;
using System.Json;

namespace NetCoreTestConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // Note that JSON keys are case sensitive, a is not same as A.

            // JSON Sample
            string jsonString = "{\"a\": 1,\"b\": \"string value\",\"c\":[{\"Value\": 1}, {\"Value\": 2,\"SubObject\":[{\"SubValue\":3}]}]}";

            // You can use the following line in a beautifier/JSON formatted for better view
            // {"a": 1,"b": "string value","c":[{"Value": 1}, {"Value": 2,"SubObject":[{"SubValue":3}]}]}

            /* Formatted jsonString for viewing purposes:
            {
               "a":1,
               "b":"string value",
               "c":[
                  {
                     "Value":1
                  },
                  {
                     "Value":2,
                     "SubObject":[
                        {
                           "SubValue":3
                        }
                     ]
                  }
               ]
            }
            */

            // Verify your JSON if you get any errors here
            JsonValue json = JsonValue.Parse(jsonString);

            // int test
            if (json.ContainsKey("a"))
            {
                int a = json["a"]; // type already set to int
                Console.WriteLine("json[\"a\"]" + " = " + a);
            }

            // string test
            if (json.ContainsKey("b"))
            {
                string b = json["b"];  // type already set to string
                Console.WriteLine("json[\"b\"]" + " = " + b);
            }

            // object array test
            if (json.ContainsKey("c") && json["c"].JsonType == JsonType.Array)
            {
                // foreach loop test
                foreach (JsonValue j in json["c"])
                {
                    Console.WriteLine("j[\"Value\"]" + " = " + j["Value"].ToString());
                }

                // multi level key test
                Console.WriteLine("json[\"c\"][0][\"Value\"]" + " = " + json["c"][0]["Value"].ToString());
                Console.WriteLine("json[\"c\"][0][\"Value\"]" + " = " + json["c"][1]["Value"].ToString());
                Console.WriteLine("json[\"c\"][1][\"SubObject\"][0][\"SubValue\"]" + " = " + json["c"][1]["SubObject"][0]["SubValue"].ToString());
            }

            Console.WriteLine();
            Console.Write("Press any key to exit.");
            Console.ReadKey();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Bru*_*ira 9

使用此工具生成基于您的json的类:

http://json2csharp.com/

然后使用该类反序列化您的json。例:

public class Account
{
    public string Email { get; set; }
    public bool Active { get; set; }
    public DateTime CreatedDate { get; set; }
    public IList<string> Roles { get; set; }
}


string json = @"{
  'Email': 'james@example.com',
  'Active': true,
  'CreatedDate': '2013-01-20T00:00:00Z',
  'Roles': [
    'User',
    'Admin'
  ]
}";

Account account = JsonConvert.DeserializeObject<Account>(json);

Console.WriteLine(account.Email);
// james@example.com
Run Code Online (Sandbox Code Playgroud)

参考:https : //forums.asp.net/t/1992996.aspx ? Nested+ Json+ Deserialization+ to+C+ object+ and+使用/html/DeserializeObject.htm


Muh*_*ais 6

尝试以下代码:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("URL");
JArray array = new JArray();
using (var twitpicResponse = (HttpWebResponse)request.GetResponse())
using (var reader = new StreamReader(twitpicResponse.GetResponseStream()))
{
    JavaScriptSerializer js = new JavaScriptSerializer();
    var objText = reader.ReadToEnd();

    JObject joResponse = JObject.Parse(objText);
    JObject result = (JObject)joResponse["result"];
    array = (JArray)result["Detail"];
    string statu = array[0]["dlrStat"].ToString();
}
Run Code Online (Sandbox Code Playgroud)


Vik*_*ani 6

如果 JSON 是动态的,如下所示

{
 "Items": [{
        "Name": "Apple",
        "Price": 12.3
    },
    {
        "Name": "Grape",
        "Price": 3.21
    }
   ],
   "Date": "21/11/2010"
}
Run Code Online (Sandbox Code Playgroud)

然后,一旦您NewtonSoft.Json从 NuGet安装并将其包含在您的项目中,您就可以将其序列化为

string jsonString = "{\"Items\": [{\"Name\": \"Apple\",\"Price\": 12.3},{\"Name\": \"Grape\",\"Price\": 3.21}],\"Date\": \"21/11/2010\"}";

        dynamic DynamicData = JsonConvert.DeserializeObject(jsonString);

        Console.WriteLine(   DynamicData.Date); // "21/11/2010"
        Console.WriteLine(DynamicData.Items.Count); // 2
        Console.WriteLine(DynamicData.Items[0].Name); // "Apple"
Run Code Online (Sandbox Code Playgroud)

来源:如何在 C# 中读取 JSON 数据(使用控制台应用程序和 ASP.NET MVC 的示例)?


Tar*_*ity 5

我认为来自msdn站点的以下内容是否有助于为您正在寻找的内容提供一些本机功能。请注意,它是为 Windows 8 指定的。下面列出了该站点的一个此类示例。

JsonValue jsonValue = JsonValue.Parse("{\"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"IDs\": [116, 943, 234, 38793]}");
double width = jsonValue.GetObject().GetNamedNumber("Width");
double height = jsonValue.GetObject().GetNamedNumber("Height");
string title = jsonValue.GetObject().GetNamedString("Title");
JsonArray ids = jsonValue.GetObject().GetNamedArray("IDs");
Run Code Online (Sandbox Code Playgroud)

它利用Windows.Data.JSON命名空间。

  • 不错,但是“最低支持的客户端:Windows 8” (6认同)
  • @virtouso,正如 watbywbarif 指出的那样,它实际上是相当新的,但是 [Microsoft](https://msdn.microsoft.com/en-us/library/ie/windows.data.json) 的支持最少,仅适用于 Windows 8 . (3认同)

归档时间:

查看次数:

1026929 次

最近记录:

5 年,11 月 前