我有以下代码。
var user = (Dictionary<string, object>)serializer.DeserializeObject(responsecontent);
responsecontent
中的输入是JSON,但它没有被正确解析为一个对象。我应该如何正确地反序列化它?
我假设你没有使用Json.NET(Newtonsoft.Json NuGet软件包)。如果是这样的话,那么你应该试试。
它有以下特点。
1.LINQ到JSON 2.JsonSerializer用于快速将你的.NET对象转换为JSON,然后再转换回来。 3.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);
正如这里所回答的那样--[将JSON反序列化为C#动态对象?][1] 。
使用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;
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][1]的更多信息,请参见链接。
更新.现在最简单的方法是使用[NuGet包][2]来获取 "Web.Helpers"。
现在获取Web.Helpers
的最简单方法是使用[NuGet包][2]。
如果你不关心早期的windows版本,你可以使用[Windows.Data.Json
][3]命名空间的类。
// 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());
[1]: http://msdn.microsoft.com/en-us/library/system.web.helpers.json%28v=vs.111%29.aspx [2]: https://www.nuget.org/packages/Microsoft.AspNet.WebHelpers/ [3]: https://msdn.microsoft.com/en-us/library/windows/apps/xaml/windows.data.json.aspx
如果.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是很好的...
另一个本机解决方案是JavaScriptSerializer,它不需要任何第三方库,只需要引用System.Web.Extensions。 这并不是一个新的功能,而是自3.5以来一个非常不为人知的内置功能。
using System.Web.Script.Serialization;
..
JavaScriptSerializer serializer = new JavaScriptSerializer();
objectString = serializer.Serialize(new MyObject());
而后
MyObject o = serializer.Deserialize<MyObject>(objectString)
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();
}
}
}
使用这个工具来生成一个基于你的json的类。
然后使用该类来反序列化你的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': '[email protected]',
'Active': true,
'CreatedDate': '2013-01-20T00:00:00Z',
'Roles': [
'User',
'Admin'
]
}";
Account account = JsonConvert.DeserializeObject<Account>(json);
Console.WriteLine(account.Email);
// [email protected]
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': '[email protected]',
'Active': true,
'CreatedDate': '2013-01-20T00:00:00Z',
'Roles': [
'User',
'Admin'
]
}";
Account account = JsonConvert.DeserializeObject<Account>(json);
Console.WriteLine(account.Email);
// [email protected]
参考文献。 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();
}
以下来自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");
它利用[Windows.Data.JSON][2]命名空间。
1:
[2]: https://msdn.microsoft.com/en-us/library/windows/apps/xaml/windows.data.json.aspx
我认为我看到的最好的答案是@MD_Sayem_Ahmed。
你的问题是"如何用C#解析Json",但看起来你是想对Json进行解码。 如果你想解码它,Ahmed'的答案是好的。
如果您想在 ASP.NET Web Api 中实现这个目标,最简单的方法是创建一个数据传输对象,该对象保存了您想要分配的数据。
public class MyDto{
public string Name{get; set;}
public string Value{get; set;}
}
你只需在你的请求中添加application/json头(例如,如果你使用Fiddler)。 然后,你将在ASP.NET Web API中使用这个头,如下所示。
//controller method -- assuming you want to post and return data
public MyDto Post([FromBody] MyDto myDto){
MyDto someDto = myDto;
/*ASP.NET automatically converts the data for you into this object
if you post a json object as follows:
{
"Name": "SomeName",
"Value": "SomeValue"
}
*/
//do some stuff
}
当我在Web Api工作时,这对我帮助很大,让我的生活变得超级轻松。
string json = @"{
'Name': 'Wide Web',
'Url': 'www.wideweb.com.br'}";
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
dynamic j = jsonSerializer.Deserialize<dynamic>(json);
string name = j["Name"].ToString();
string url = j["Url"].ToString();
.net core 3.0内置了[System.Text.Json
][1],这意味着你现在可以反序列化/序列化JSON 而无需使用第三方库。
要将你的类序列化为JSON字符串。
var json = JsonSerializer.Serialize(order);
将JSON反序列化为一个强类型的类。
var order = JsonSerializer.Deserialize<Order>(json);
所以如果你有一个像下面这样的类。
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
需要注意的是,当使用你自己的代码时,System.Text.Json
不会自动处理camelCase
JSON属性(然而,当使用MVC/WebAPI请求和模型绑定器时,它会自动处理)。
所以,如果你有下面这样的JSON和上面这样的 "Order",那么它将不会反序列化到你的类中。
var json = @"{
""id"": 123456,
""orderNumber"": ""ABC-123-456"",
""balance"": 9876.54,
""opened"": ""2019-10-21T23:47:16.8513874+01:00"",
}";
为了解决这个问题,你需要传递JsonSerializerOptions
作为一个参数(不幸的是,它不可能在整个应用程序中配置这个参数)。
JsonSerializerOptions options = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase, // set camelCase
WriteIndented = true // write pretty json
};
// serialize using options
var json = JsonSerializer.Serialize(order, options);
// deserialize using options
var order = JsonSerializer.Deserialize<Order>(json, options);
System.Text.Json
也可作为Nu-get包System.Text.Json用于.Net Framework和.Net Standard。
[1]: [1]:https://docs.microsoft.com/en-us/dotnet/api/system.text.json?view=netcore-3.0 2:
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(user)))
{
// Deserialization from JSON
DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(UserListing))
DataContractJsonSerializer(typeof(UserListing));
UserListing response = (UserListing)deserializer.ReadObject(ms);
}
public class UserListing
{
public List<UserList> users { get; set; }
}
public class UserList
{
public string FirstName { get; set; }
public string LastName { get; set; }
}