我有以下代码:

var user = (Dictionary<string, object>)serializer.DeserializeObject(responsecontent);

responsecontent中的输入是JSON,但它没有正确地反序列化为对象。我应该如何正确地反序列化它?


当前回答

System.Text.Json

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

Serialize / Deserialize

序列化你的类到JSON字符串:

var json = JsonSerializer.Serialize(model);

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

var model = JsonSerializer.Deserialize<Model>(json);

解析(。6)净

. net 6引入了System.Text.Json.Nodes命名空间,使DOM能够以类似于Newtonsoft的方式进行解析、导航和操作。Json使用新的类JsonObject, JsonArray, JsonValue和JsonNode。

// JsonObject parse DOM
var jsonObject = JsonNode.Parse(jsonString).AsObject();
// read data from DOM
string name = jsonObject["Name"].ToString();
DateTime date = (DateTime)jsonObject["Date"];
var people = jsonObject["People"].Deserialize<List<Person>>();

类似的方法也适用于JsonArray。这个答案提供了关于JsonObject的更多细节。


需要注意的一点是,System.Text.Json在使用自己的代码时不会自动处理camelCase JSON属性(然而,当使用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);

System.Text.Json也可用于.Net Framework和.Net Standard,作为一个nuget包System.Text.Json

Edit

在。net 6中,JsonNode.Parse()提供了解析“未知”json的功能

其他回答

如果您可以使用。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);

最后一个控制台。WriteLine很贴心…

System.Text.Json

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

Serialize / Deserialize

序列化你的类到JSON字符串:

var json = JsonSerializer.Serialize(model);

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

var model = JsonSerializer.Deserialize<Model>(json);

解析(。6)净

. net 6引入了System.Text.Json.Nodes命名空间,使DOM能够以类似于Newtonsoft的方式进行解析、导航和操作。Json使用新的类JsonObject, JsonArray, JsonValue和JsonNode。

// JsonObject parse DOM
var jsonObject = JsonNode.Parse(jsonString).AsObject();
// read data from DOM
string name = jsonObject["Name"].ToString();
DateTime date = (DateTime)jsonObject["Date"];
var people = jsonObject["People"].Deserialize<List<Person>>();

类似的方法也适用于JsonArray。这个答案提供了关于JsonObject的更多细节。


需要注意的一点是,System.Text.Json在使用自己的代码时不会自动处理camelCase JSON属性(然而,当使用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);

System.Text.Json也可用于.Net Framework和.Net Standard,作为一个nuget包System.Text.Json

Edit

在。net 6中,JsonNode.Parse()提供了解析“未知”json的功能

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

{
 "Items": [{
        "Name": "Apple",
        "Price": 12.3
    },
    {
        "Name": "Grape",
        "Price": 3.21
    }
   ],
   "Date": "21/11/2010"
}

然后,一旦你安装了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"

来源:如何在c#中读取JSON数据(使用控制台应用程序和ASP的例子)。净MVC) ?

使用这个工具在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

引用: https://forums.asp.net/t/1992996.aspx?Nested+Json+Deserialization+to+C+object+and+using+that+object https://www.newtonsoft.com/json/help/html/DeserializeObject.htm

系统。Json现在工作了…

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

PM> Install-Package System.Json -Version 4.5.0

示例:

// 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();
        }
    }
}