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包).如果是这种情况,那么你应该尝试一下.
它具有以下功能:
看下面的例子.在此示例中,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)
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)
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)
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很可爱......
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)
hal*_*ldo 21
.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
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)
使用此工具生成基于您的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': '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
尝试以下代码:
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)
如果 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 的示例)?
我认为来自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命名空间。
| 归档时间: |
|
| 查看次数: |
1026929 次 |
| 最近记录: |