【问题标题】:parsing the result of web api解析web api的结果
【发布时间】:2022-01-11 00:39:32
【问题描述】:

我是 web api 的新手。我已经调用了一个外部 web api

 var url = "http://service.mydomain.com/api/GetItems";

 var parameters = new Dictionary<string, string>();
 parameters["id"] = "10";
 using (HttpClient client = new HttpClient())
 {
     var post = client.PostAsync(url, new FormUrlEncodedContent(parameters)).Result;
     if (post.IsSuccessStatusCode)
     {                   
        var result = post.Content.ReadAsStringAsync();                    
     }
 }

结果值为

"{\"Status\":1,\"Data\":{\"state\":1,\"message\":\"Done Successfully\",\"WorkName\":\"test\",\"WorkUrl\":\"192.168.1.10/go\"},\"Message\":null}"

如何访问结果值的任何项目

【问题讨论】:

    标签: api asp.net-web-api asp.net-web-api2


    【解决方案1】:

    您可以创建一个与预期的 json 响应布局相匹配的类,然后反序列化。

    public class MyModelData
    {
        public int State { get; set; }
        public string Message { get; set; }
        public string WorkName { get; set; }
        public string WorkUrl { get; set; }
    }
    public class MyModel
    {
        public int Status { get; set; }
        public MyModelData Data { get; set; }
        public string Message { get; set; }
    }
    

    然后使用:

    string result = post.Content.ReadAsStringAsync();
    MyModel model = JsonSerializer.Deserialize<MyModel>(result);
    

    MyModel model = post.Content.ReadAsJsonAsync();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-19
      • 1970-01-01
      • 1970-01-01
      • 2020-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多