【问题标题】:Parsing JSON Name Pair in C#在 C# 中解析 JSON 名称对
【发布时间】:2017-03-31 18:12:14
【问题描述】:

使用 C# 解析 JSON URL 我遇到了一些问题。如您所知,JSON 数据以名称/值对的形式编写。现在在 URL JSON 中我有这些数据:

{  
   "currentVersion":10.41,
   "serviceDescription":"There are some text here",
   "hasVersionedData":true,
   "supportsDisconnectedEditing":false,
   "syncEnabled":false,
   "supportedQueryFormats":"JSON",
   "maxRecordCount":1000
 }

我只想使用此代码打印出 JSON 数据的名称部分

using (var wc = new WebClient())
{
    string json = wc.DownloadString("http://xxxxxxxxx?f=pjson");
    try
    {
        dynamic data = Json.Decode(json);
        for (int i = 0; i <= data.Length - 1; i++)
        {
            Console.WriteLine(data[0]);
        }

    }
    catch (Exception e)
    {

    }
}

但这并没有在控制台上打印任何东西!你能告诉我我做错了什么吗?

【问题讨论】:

  • 您遇到什么错误?你正在吃掉例外。尝试写入控制台并查看错误
  • 我没有收到任何错误!只需使用控制台
  • 当你忽略异常时,你怎么知道你没有得到错误?
  • 我已经在 catch 上写下了控制台,所以没有错误

标签: c# json


【解决方案1】:

使用Newtonsoft JSON:

JObject jsonObject = JObject.Parse(json);
foreach(var jsonItem in jsonObject)
{
    Console.WriteLine(jsonItem.Key);
}
Console.ReadKey();

【讨论】:

    【解决方案2】:

    创建一个对象来保存结果

    public class RootObject
    {
        public double currentVersion { get; set; }
        public string serviceDescription { get; set; }
        public bool hasVersionedData { get; set; }
        public bool supportsDisconnectedEditing { get; set; }
        public bool syncEnabled { get; set; }
        public string supportedQueryFormats { get; set; }
        public int maxRecordCount { get; set; }
    }
    

    使用 JavaScriptSerializer 反序列化结果。

    var serializer = new JavaScriptSerializer();
    var rootObject= serializer.Deserialize<RootObject>(json);
    
    Console.WriteLine(rootObject.currentVersion);
    Console.WriteLine(rootObject.serviceDescription);
    etc.
    

    【讨论】:

      【解决方案3】:

      如果您在 Debug 下运行此程序,请参阅此处:Attempt by method 'System.Web.Helpers.Json..cctor()' to access method 'System.Web.Helpers.Json.CreateSerializer()' failed 一旦我取消选中启用它运行的 Visual Studio 托管进程并产生结果。但是,为了得到我认为你想要的(我切换到 foreach 的每个键/值对的列表,它很好地打印出来:

      try   
      
          {    
              var data = Json.Decode(jsonData);    
              //for (var i = 0; i <= data.Length - 1; i++)    
              foreach (var j in data)    
              {    
                  Console.WriteLine(j);    
              }    
          }    
          catch (Exception e)    
          {    
              Console.WriteLine(e);    
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-07
        相关资源
        最近更新 更多