我有以下代码:
var user = (Dictionary<string, object>)serializer.DeserializeObject(responsecontent);
responsecontent中的输入是JSON,但它没有正确地反序列化为对象。我应该如何正确地反序列化它?
我有以下代码:
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的功能
其他回答
我假设你没有使用Json。净(Newtonsoft。Json NuGet包)。如果是这样的话,你应该试试。
它具有以下特点:
LINQ到JSON JsonSerializer用于快速将.NET对象转换为JSON并再转换回来 Json。NET可以选择生成格式良好、缩进的JSON以供调试或显示 可以将JsonIgnore和JsonProperty等属性添加到类中,以自定义类的序列化方式 能够将JSON转换为XML 支持多种平台:.NET、Silverlight和Compact Framework
请看下面的例子。在本例中,JsonConvert类用于将对象与JSON进行转换。它有两个用于此目的的静态方法。它们是SerializeObject(Object obj)和DeserializeObject<T>(String json):
using Newtonsoft.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);
如果您可以使用。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很贴心…
您还可以查看DataContractJsonSerializer
如果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) ?
下面是一个使用csc v2.0.0.61501的完整的可运行示例。
包:
nuget install Microsoft.AspNet.WebApi.Core
nuget install Microsoft.Net.Http
nuget install Newtonsoft.Json
代码:
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Threading.Tasks;
public static class App
{
static void Main()
{
MainAsync().GetAwaiter().GetResult();
}
static async Task MainAsync()
{
string url = "https://httpbin.org/get";
var client = new HttpClient();
// The verbose way:
//HttpResponseMessage response = await client.GetAsync(url);
//response.EnsureSuccessStatusCode();
//string responseBody = await response.Content.ReadAsStringAsync();
// Or:
string responseBody = await client.GetStringAsync(url);
var obj = JsonConvert.DeserializeObject<dynamic>(responseBody);
Console.WriteLine(obj);
Console.WriteLine(obj.headers.Host);
}
}
编译器命令:
csc http_request2.cs -r:".\Microsoft.AspNet.WebApi.Core.5.2.9\lib\net45\System.Web.Http.dll" -r:".\Microsoft.Net.Http.2.2.29\lib\net40\System.Net.Http.dll" -r:".\Newtonsoft.Json.13.0.1\lib\net45\Newtonsoft.Json.dll"
输出:
{
"args": {},
"headers": {
"Host": "httpbin.org",
"X-Amzn-Trace-Id": "Root=1-633dce52-64f923bb42c99bf46f78672c"
},
"origin": "98.51.7.199",
"url": "https://httpbin.org/get"
}
httpbin.org
无法加载Newtonsoft.json文件或程序集。系统无法找到指定的文件,我不得不将Newtonsoft.Json.dll移到已编译的二进制文件旁边。