如何使用C#解析JSON?

如何使用C#解析JSON?,c#,json,parsing,json.net,deserialization,C#,Json,Parsing,Json.net,Deserialization,我有以下代码: var user = (Dictionary<string, object>)serializer.DeserializeObject(responsecontent); HttpWebRequest request = (HttpWebRequest)WebRequest.Create("URL"); JArray array = new JArray(); using (var twitpicResponse = (HttpWebResponse)request

我有以下代码:

var user = (Dictionary<string, object>)serializer.DeserializeObject(responsecontent);
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();
}
var user=(字典)序列化程序。反序列化对象(responsecontent);

responsecontent
中的输入是JSON,但未正确解析为对象。我应该如何正确地反序列化它?

我假设您没有使用(Newtonsoft.Json NuGet包)。如果是这种情况,那么你应该试试

它具有以下特点:

  • LINQ到JSON
  • JsonSerializer,用于快速将.NET对象转换为JSON并再次转换
  • Json.NET可以选择性地生成格式良好、缩进的Json,用于调试或显示
  • 可以将
    JsonIgnore
    JsonProperty
    等属性添加到类中,以自定义类的序列化方式
  • 能够将JSON转换为XML或从XML转换为JSON
  • 支持多种平台:.NET、Silverlight和Compact Framework
  • 看看下面的图片。在本例中,类用于将对象与JSON进行转换。为此,它有两种静态方法。它们是:

    产品产品=新产品();
    product.Name=“苹果”;
    产品有效期=新的日期时间(2008年12月28日);
    产品价格=399万元;
    product.size=新字符串[]{“小”、“中”、“大”};
    字符串json=JsonConvert.SerializeObject(产品);
    //{
    //“名称”:“苹果”,
    //“到期日”:“2008-12-28:00:00”,
    //“价格”:3.99,
    //“尺寸”:[
    //“小”,
    //“中等”,
    //“大”
    //  ]
    //}
    Product deserializedProduct=JsonConvert.DeserializeObject(json);
    
    如果.NET 4对您可用,请查看:

    以下是该网站的一个片段:

    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非常可爱…

    您也可以看看这里回答的

    -

    使用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);
    
    有关详细信息,请参阅链接

    更新:现在获取
    Web.Helpers的最简单方法是使用


    如果您不关心早期的windows版本,则可以使用命名空间的类:

    // 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());
    

    另一个本机解决方案是JavaScriptSerializer,它不需要任何第三方库,而是对System.Web.Extensions的引用。这不是一个新的,但一个非常未知的内置功能,因为3.5

    using System.Web.Script.Serialization;
    

    回来

    MyObject o = serializer.Deserialize<MyObject>(objectString)
    
    MyObject o=序列化程序。反序列化(objectString)
    
    我认为网站上的以下内容有助于为您所寻找的内容提供一些本机功能。请注意,它是为Windows 8指定的。下面列出了该网站的一个这样的例子

    JsonValue-JsonValue=JsonValue.Parse(“{”宽度\“:800,\”高度\“:600,\”标题\“:\”从15楼查看\“,\”ID \“:[116943234,38793]”);
    double width=jsonValue.GetObject().GetNamedNumber(“宽度”);
    double height=jsonValue.GetObject().GetNamedNumber(“高度”);
    字符串title=jsonValue.GetObject().GetNamedString(“title”);
    JsonArray id=jsonValue.GetObject().GetNamedArray(“id”);
    

    它使用名称空间。

    请尝试以下代码:

    var user = (Dictionary<string, object>)serializer.DeserializeObject(responsecontent);
    
    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();
    }
    

    我认为我见过的最好的答案是“MD_Sayem_Ahmed”

    您的问题是“如何用C#解析Json”,但您似乎想要解码Json。如果你想解码它,艾哈迈德的答案是好的

    如果要在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时帮了我很大的忙,使我的生活变得非常轻松。

    var result=controller.ActioName(objParams);
    
    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"]);
    
    IDictionary data=(IDictionary)new System.Web.Routing.RouteValueDictionary(result.data); AreEqual(“表已经存在”,数据[“消息]);
    System.Json现在可以工作了

    安装nuget

    样本

    // 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': '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
    
    公共类帐户
    {
    公共字符串电子邮件{get;set;}
    公共bool活动{get;set;}
    公共日期时间CreatedDate{get;set;}
    公共IList角色{get;set;}
    }
    字符串json=@”{
    “电子邮件”:james@example.com',
    “活动”:正确,
    “CreatedDate”:“2013-01-20T00:00:00Z”,
    “角色”:[
    “用户”,
    “管理员”
    ]
    }";
    Account=JsonConvert.DeserializeObject
    
    字符串json=@”{
    “名称”:“万维网”,
    “Url”:“www.wideweb.com.br'}”;
    JavaScriptSerializer jsonSerializer=新的JavaScriptSerializer();
    动态j=jsonSerializer.Deserialize(json);
    string name=j[“name”].ToString();
    字符串url=j[“url”].ToString();
    
    使用(var ms=new MemoryStream(Encoding.Unicode.GetBytes(user)))
    {
    //从JSON反序列化
    DataContractJsonSerializer反序列化器=新的DataContractJsonSerializer(typeof(UserListing))
    DataContractJsonSerializer(typeof(UserListing));
    UserListing响应=(UserListing)反序列化程序.ReadObject(ms);
    }
    公共类用户列表
    {
    公共列表用户{get;set;}
    }
    公共类用户列表
    {
    公共字符串名{get;set;}
    公共字符串LastName{get;set;}
    }
    
    System.Text.Json 3.0自带了内置接口,这意味着您可以反序列化JSON,而无需使用第三方库

    要将类序列化为JSON字符串:

    var json = JsonSerializer.Serialize(order);
    
    要将JSON反序列化为强类型类,请执行以下操作:

    var order = JsonSerializer.Deserialize<Order>(json);
    

    System.Text.Json作为Nu get包也可用于.Net Framework和.Net标准

    您可以使用以下扩展

    public static class JsonExtensions
    {
        public static T ToObject<T>(this string jsonText)
        {
            return JsonConvert.DeserializeObject<T>(jsonText);
        }
    
        public static string ToJson<T>(this T obj)
        {
            return JsonConvert.SerializeObject(obj);
        } 
    }
    
    公共静态类JsonEx
    
    var json = JsonSerializer.Serialize(order);
    
    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
    
    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);
    
    public static class JsonExtensions
    {
        public static T ToObject<T>(this string jsonText)
        {
            return JsonConvert.DeserializeObject<T>(jsonText);
        }
    
        public static string ToJson<T>(this T obj)
        {
            return JsonConvert.SerializeObject(obj);
        } 
    }
    
    {
     "Items": [{
            "Name": "Apple",
            "Price": 12.3
        },
        {
            "Name": "Grape",
            "Price": 3.21
        }
       ],
       "Date": "21/11/2010"
    }
    
    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"