var user = (Dictionary<string, object>)serializer.DeserializeObject(responsecontent);
输入的
responsecontent
是JSON格式的,但是没有正确地反序列化为一个对象。我应该如何正确地反序列化它?var user = (Dictionary<string, object>)serializer.DeserializeObject(responsecontent);
responsecontent
是JSON格式的,但是没有正确地反序列化为一个对象。我应该如何正确地反序列化它?我假设您没有使用Json.NET库(Newtonsoft.Json NuGet包)。如果是这种情况,那么您应该尝试一下它。
它具有以下功能:
JsonIgnore
和JsonProperty
,以自定义序列化方式请查看下面的示例。在此示例中,JsonConvert
类用于将对象转换为JSON格式并从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);
JSON.parse('{"Expiry": "2008-12-28T00:00:00"}').Expiry
返回的是 字符串 "2008-12-28T00:00:00"
,而不是日期。可以通过 new Date(str)
将其转换为 Date
,但是 JSON.parse
对日期一无所知。你需要传入一个检查每个字符串值是否符合模式的reviver。" - T.J. Crowder正如在这里回答的那样 - 将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;
或者使用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;
以下是一些不使用第三方库的选项:
// 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);
请查看链接以获取有关 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());
如果你可以使用.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);
那个最后的 Console.WriteLine 很不错...
除了需要引用System.Web.Extensions,并不需要任何第三方库的本地解决方案是使用JavaScriptSerializer。虽然这不是什么新东西,但自3.5以来一直存在,而且非常不为人知。
using System.Web.Script.Serialization;
..
JavaScriptSerializer serializer = new JavaScriptSerializer();
objectString = serializer.Serialize(new MyObject());
并返回
MyObject o = serializer.Deserialize<MyObject>(objectString)
.NET Core 3.0自带 System.Text.Json
,这意味着你可以在不使用第三方库的情况下对JSON进行反序列化/序列化。
将你的类序列化为JSON字符串:
var json = JsonSerializer.Serialize(model);
将JSON反序列化为强类型类:
var model = JsonSerializer.Deserialize<Model>(json);
.NET 6引入了System.Text.Json.Nodes 命名空间,该命名空间使用新类JsonObject
、JsonArray
、JsonValue
和 JsonNode
,以类似于 Newtonsoft.Json 的方式实现 DOM 解析、导航和操作。
// 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也可作为一个Nu-get包在.Net Framework和.Net Standard中使用 System.Text.Json
在.NET 6中,JsonNode.Parse()提供解析“未知”json的功能。
JsonDocument.Parse
进行解析。 - haldoJsonNode.Parse()
提供了解析“未知” JSON 的功能。 - haldo现在System.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();
}
}
}
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
References: 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
请尝试下面的代码:
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();
}
System.Web.Helpers
中有Json
,在System.ServiceModel.Web
中有JsonQueryStringConverter
,在System.Web.Script.Serialization
中有JavascriptSerializer
,在System.Runtime.Serialization.Json
中有DataContractJsonSerializer
,甚至MS都决定在其ASP.NET Web API中包括第三方Json.NET
。如果你觉得这还不够,MS正在开发System.Json
,但目前不适合使用。微软太棒了,我选择最好看的命名空间。 - nawfalWindows.Data.Json
中还有JsonValue
,仅适用于 Windows 8 及以上版本。我很喜欢它。微软正在使命中 :) - nawfal