简体   繁体   English

如何使用 ASP.net 框架使用 API?

[英]How do I consume an API using ASP.net Framework?

Sample Json:示例 Json:

{
  "success": true,
  "status": 200,
  "data": [
    {
      "ProfileID": "1001",
      "Name": "Jane Doe",
      "HomePhone": "555-1212",
      "Address1": "123 Elm St"
    },
    {
      "ProfileID": "1002",
      "Name": "Rick Fox",
      "HomePhone": "555-1213",
      "Address1": "123 Ok St"
    }
  ]
}

My code so far:到目前为止我的代码:

using Newtonsoft.Json;

private void popGrid()
{
   var client = new HttpClient();
   client.BaseAddress = new Uri("http://the-api/");
   var responseTask = client.GetAsync("member-list");
   responseTask.Wait();
   var result = responseTask.Result;
   if (result.IsSuccessStatusCode)
   {
      var read_response = responseTask.Result.Content.ReadAsStringAsync();
      read_response.Wait();
      var read_result = read_response.Result;

      dynamic response = JsonConvert.DeserializeObject(read_result);
      var success = response.success;
      var status = response.status;
      var data = response.data;

      // List<Root> myDeserializedClass = JsonConvert.DeserializeObject<List<Root>>(data);

      if ((bool)success)
      {
         GridView1.DataSource = data;
         GridView1.DataBind();
      }
   }

}

public class Root
{
   public string ProfileID { get; set; }
   public string Name { get; set; }
   public string HomePhone { get; set; }
   public string Address1 { get; set; }
}

The Errors: If I run the code as written, it runs through all the way without issue.错误:如果我按照编写的方式运行代码,它会一直运行而没有问题。 However when the page renders I get an ugly error:但是,当页面呈现时,我得到一个丑陋的错误:

    Type 'Newtonsoft.Json.Linq.JValue' in Assembly 'Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' is not marked as serializable.

Buried in the Stack Trace is one line that gives a clue(to me):埋在堆栈跟踪中的一行提供了一个线索(对我来说):

    [ArgumentException: Error serializing value '1001' of type 'Newtonsoft.Json.Linq.JValue.']

So then I the added the (commented) line that uses the Root class .然后我添加了使用 Root 类的(注释的)行 However, if I un-comment that line and run the code, I get the following error:但是,如果我取消注释该行并运行代码,我会收到以下错误:

    Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'The best overloaded method match for 'Newtonsoft.Json.JsonConvert.DeserializeObject<System.Collections.Generic.List<Root>>(string)' has some invalid arguments'

The above error seems to indicate that JsonConvert.DeserializeObject won't accept the var 'data' as an input.上述错误似乎表明 JsonConvert.DeserializeObject 不会接受 var 'data' 作为输入。 Any thoughts would be greatly appreciated.任何想法将不胜感激。

You can simplify the approach.您可以简化方法。 Instead of trying to deserialize only part of the JSON, deserialize the whole thing into an object.与其尝试仅反序列化 JSON 的一部分,不如将整个内容反序列化为一个对象。 Define an object structure which matches it:定义一个与之匹配的对象结构:

public class Root
{
    public bool success { get; set; }
    public int status { get; set; }
    public IEnumerable<Profile> data { get; set; }
}

public class Profile
{
    public string ProfileID { get; set; }
    public string LastName { get; set; }
    public string FirstName { get; set; }
    public string HomePhone { get; set; }
}

Then deserialize the response into that:然后将响应反序列化为:

var result = JsonConvert.DeserializeObject<Root>(read_result);

Then you can access the collection in that object:然后您可以访问该对象中的集合:

GridView1.DataSource = result.data;

it is better to create async method , but if you can not , you have to fix your code最好创建异步方法,但如果你不能,你必须修复你的代码

    var response = client.GetAsync(api).Result;
    if (response.IsSuccessStatusCode)
    {
     var json = response.Content.ReadAsStringAsync().Result;
     var jsonParsed=JObject.Parse(json);
     var success = jsonParsed["success"];
      var status = jsonParsed["status"];
      List<Root> data = jsonParsed["data"].ToObject<List<Root>>();
    
      //or in this case you don't need any custom classes at all

       DataTable data = jsonParsed["data"].ToObject<DataTable>();
      
    
      if ((bool)success)
      {
         GridView1.DataSource = data;
         GridView1.DataBind();
      }

     } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM