使用 C# 从外部 api 读取 json 数据

Posted

技术标签:

【中文标题】使用 C# 从外部 api 读取 json 数据【英文标题】:Reading json data from external api using C# 【发布时间】:2019-03-22 04:04:51 【问题描述】:

我正在尝试读取来自 api 的 json 数据,我只想从这些数据中读取对象..

 string id_url = "http://abc/some_id";

 WebRequest requst = WebRequest.Create(id_url);
 requst.Method = "GET";
 requst.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("user:password"));

 HttpWebResponse response = requst.GetResponse() as HttpWebResponse;

 var encod = ASCIIEncoding.ASCII;

 using (var readchat = new System.IO.StreamReader(response.GetResponseStream(), encod))
 
     string chatresult = readchat.ReadToEnd();

     var json = JObject.Parse(chatresult);
 

我得到json


      "comment": null,
      "triggered_response": true,
      "rating": null,
      "visitor": 
        "phone": "",
        "name": "abc"
      ,

      "history": [
        
          "name": "Visitor 7949",
          "department_name": null,
          "type": "chat.memberjoin",
          "department_id": null
        ,
        
          "name": "fdef",
          "sender_type": "Trigger",
          "msg": "Welcome back! How may I help you today?",
          "type": "chat.msg"        
        ,
        
          "name": "use",
          "sender_type": "Trigger",
          "msg": "good morning",
          "type": "chat.msg"        
        
      ]

我必须使用 C# 仅从 json 读取“msg”标签数据。我试过这个:

string data = json["history"].ToString();

通过上面的使用,我从“历史”标签中获取数据,但是如何能够像我们使用 javascript ajax 一样从历史 [array].msg 中获取文本。

【问题讨论】:

json 是否有效已使用jsonformatter.curiousconcept.com 进行检查 Load JSON data into a C# Class的可能重复 【参考方案1】:

您可以将JsonConvert 与动态对象JsonConvert.DeserializeObject<dynamic>(data) 一起使用

示例代码:

string data = " \"comment\": null,   \"triggered_response\": true,   \"rating\": null,   \"visitor\":     \"phone\": \"\",    \"name\": \"abc\"   ,   \"history\": [         \"name\": \"Visitor 7949\",     \"department_name\": null,     \"type\": \"chat.memberjoin\",     \"department_id\": null    ,         \"name\": \"fdef\",     \"sender_type\": \"Trigger\",     \"msg\": \"Welcome back! How may I help you today?\",     \"type\": \"chat.msg\"        ,     \"name\": \"use\",     \"sender_type\": \"Trigger\",     \"msg\": \"good morning\",     \"type\": \"chat.msg\"           ]  ";

var dynamicobject = JsonConvert.DeserializeObject<dynamic>(data);

var historyname = dynamicobject.history[0].name.ToString();

【讨论】:

【参考方案2】:
  //data structure for mapping
public class History 
  public string name  get; set; 
  public string sender_type  get; set; 
  public string msg  get; set; 
  public string type  get; set; 


public class Visitor 
  public string Phone  get; set; 
  public string Name  get; set; 



public class ObjectThatContainsHistory 
  public string Comment  get; set; 
  public bool Triggered_Response  get; set; 
  public string Rating  get; set; 
  public Visitor Visitor  get; set; 

  public List<History> History  get; set; 


  var jsonString =
    @"
        ""comment"": null,
        ""triggered_response"": true,
        ""rating"": null,
        ""visitor"": 
          ""phone"": """",
          ""name"": ""abc""
        ,

        ""history"": [
          
            ""name"": ""Visitor 7949"",
            ""department_name"": null,
            ""type"": ""chat.memberjoin"",
            ""department_id"": null
          ,
          
            ""name"": ""fdef"",
            ""sender_type"": ""Trigger"",
            ""msg"": ""Welcome back! How may I help you today?"",
            ""type"": ""chat.msg""        
          ,
          
            ""name"": ""use"",
            ""sender_type"": ""Trigger"",
            ""msg"": ""good morning"",
            ""type"": ""chat.msg""        
          
        ]
    ";

  ObjectThatContainsHistory objectThatContainsHistory = JsonConvert.DeserializeObject<ObjectThatContainsHistory>(jsonString);

  var messages = objectThatContainsHistory.History
    .Select(x => x.msg)
    .ToList();

【讨论】:

以上是关于使用 C# 从外部 api 读取 json 数据的主要内容,如果未能解决你的问题,请参考以下文章

C# 无法从 API 调用读取 json 响应

通过 HTTP 请求使用 C# 读取 Json

Node.js 和 JSON:从外部网站 api 检索信息

C# 中使用HttpClient读取大型Json数据集

如何使用 c# 读取 asp.net 中的 json 响应(经销商俱乐部域检查可用性 API 集成)

用于使用 Azure SQL Server 数据的 C# Web API