How can I parse JSON with C#?
我有以下代码:
1 | var user = (Dictionary<string, object>)serializer.DeserializeObject(responsecontent); |
我假设您没有使用json.net(newtonsoft.json nuget包)。如果是这种情况,那么你应该试试。
它具有以下特点:
看看下面的例子。在本例中,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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动态对象?
使用json.net非常简单:
1 2 3 4 | 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:
1 2 3 4 | dynamic stuff = JObject.Parse("{ 'Name': 'Jon Smith', 'Address': { 'City': 'New York', 'State': 'NY' }, 'Age': 42 }"); string name = stuff.Name; string address = stuff.Address.City; |
。
以下是一些不使用第三方库的选项:
1 2 3 4 5 6 7 8 9 10 11 12 | // 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的更多信息,请参见链接。
更新:现在获得
如果不关心早期的Windows版本,可以使用
1 2 3 4 | // 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)
以下是该站点的一个片段:
1 2 3 | 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以来非常未知的内置功能。
1 | using System.Web.Script.Serialization; |
。
…
1 2 |
然后回来
1 | MyObject o = serializer.Deserialize<MyObject>(objectString) |
。
您还可以查看DataContractJSonserializer
System.json现在工作了…
安装nuget https://www.nuget.org/packages/system.json
1 | PM> Install-Package System.Json -Version 4.5.0 |
号
样品:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 | // 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的类:
http://json2csharp.com/
然后使用类反序列化JSON。例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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?嵌套的+json+反序列化+到+c+对象+和+使用+那个+对象https://www.newtonsoft.com/json/help/html/deserializeobject.htm
尝试以下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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指定的。下面列出了站点中的一个这样的示例。
1 2 3 4 5 | 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名称空间。
我认为我所看到的最好的答案是@md yem_ahmed。
您的问题是"我如何用C解析JSON",但您似乎想要解码JSON。如果你想破译它,艾哈迈德的答案是好的。
如果要在ASP.NET Web API中完成此操作,最简单的方法是创建一个保存要分配的数据的数据传输对象:
1 2 3 4 | public class MyDto{ public string Name{get; set;} public string Value{get; set;} } |
号
您只需将application/json头添加到请求中(例如,如果您使用的是fiddler)。然后您将在ASP.NET Web API中使用它,如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 | //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的时候帮助了我很多,使我的生活变得非常简单。
1 2 3 | var result = controller.ActioName(objParams); IDictionary<string, object> data = (IDictionary<string, object>)new System.Web.Routing.RouteValueDictionary(result.Data); Assert.AreEqual("Table already exists.", data["Message"]); |
号