【问题标题】:How to interpret JSON in c#如何在 C# 中解释 JSON
【发布时间】:2017-06-19 03:55:27
【问题描述】:

我正在尝试将 cat 事实添加到我的不和谐机器人(不相关)并且我使用的网站返回一个类似于这样的 json:

{
  "facts": ["The fact is here"], 
  "success": "true"
}

网站是http://catfacts-api.appspot.com/api/facts 我只想将事实作为字符串来获取。

以下是我目前正在使用的,但当事实包含'"'时会搞砸

System.Net.WebClient wc = new System.Net.WebClient();
string thingy = wc.DownloadString("http://catfacts-api.appspot.com/api/facts");
string[] thingys = thingy.Split('"');
string fact = thingys[3];

【问题讨论】:

  • 看看 Newtonsoft.Json 库。
  • 使用 Netwonsoft.Json 将您的 JSON 字符串反序列化为 C# 对象。另请查看json2csharp.com

标签: c# json


【解决方案1】:

将 Newtonsoft.json nuget 包添加到您的项目可能会帮助您将 deserialize json 转换为适当的 Class,或者如果您只阅读几个属性,您可以使用 JObject 作为同一库的一部分。

文档:http://www.newtonsoft.com/json/help/html/SerializingJSON.htm

这是一个示例

  using Newtonsoft.json;
  Class Cats
  {
    string[] Facts {get; set;}
  } 

  var wc = new System.Net.WebClient();
  var response= wc.DownloadString("http://catfactsapi.appspot.com/api/facts");
  var cat = JsonConvert.Deserialize<Cat>(response); 
  // Access facts
  if(cat !=null && car.Facts!= null)
  {
       foreach(var fact in car.Facts)
       {
       }
  }

或者 如果只有几个属性

  var catObj = JObject.Parse(response);
  var facts = catObj["Facts"];

【讨论】:

    【解决方案2】:

    使用Json.NET

    dynamic parsedJson = JsonConvert.DeserializeObject(thingy);
    string fact = parsedJson.facts[0];
    

    这会将 json 解析为动态对象,并读取作为数组的事实字段。数组的第一个元素包含一个事实。

    如果有很多事实,你可以迭代 parsedJson.facts 这是一个字符串数组

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-21
      • 1970-01-01
      • 1970-01-01
      • 2011-01-16
      • 1970-01-01
      • 2011-08-31
      • 2013-06-28
      • 2020-09-14
      相关资源
      最近更新 更多