首页 > 解决方案 > 使用 .netcore 从 Web api 获取 JSON 数据

问题描述

我制作了一个 api,其中包含一些数据,例如www.example.com/data/select?indent=on&q=title:asthma 以 JSON 格式提供数据,例如

{
"responseHeader":{
"status":0,
"QTime":2,
"params":
{
"q":"title:asthma",
"indent":"on",
"wt":"json"
},
"response":{"numFound":1,"start":0, docs:[
{
"tstamp": "xxxx"
"id": "xxxxx"
"title": "Asthma is a medical term"
"url": "www.example.com/xxxx"
"content":"xxxxx"
}]}
}}

我想从我的 .netcore 应用程序中调用相同的 url,以便我可以从响应中获取标题和 url 并将其显示给我的 .netcore 应用程序。作为 .netcore 的新手,要习惯 MVC 架构非常棘手。我的模型看起来像这样

namespace searchEngineTesting.Models
{
    public class SearchModel
    {
        public string Title {get; set;}
        public string Source {get; set;}

    }
}

我如何使用控制器,例如每当触发器将字符串作为输入cancer并将其放在 api 的标题中并从响应中www.example.com/data/select?indent=on&q=title:cancer获取和。titleurl

标签: .net-coreasp.net-core-mvc

解决方案


您可以像下面这样获取 json 数据:

[HttpGet]
public  async Task<JsonResult> Get()
{
    var model = new SearchModel();
    var url = "https://localhost:5001/api/values/test";//it should be the url of your api
    using (var httpClient = new HttpClient())
    {
        using (var response = await httpClient.GetAsync(url))
        {
            using (var content = response.Content)
            {  
               //get the json result from your api
                var result = await content.ReadAsStringAsync();
                var root = (JObject)JsonConvert.DeserializeObject(result);
                var items = root.SelectToken("responseHeader").Children().OfType<JProperty>().ToDictionary(p => p.Name, p => p.Value);
                foreach(var item in items)
                {
                    if(item.Key== "response")
                    {
                        var key = item.Value.SelectToken("").OfType<JProperty>().ToDictionary(p => p.Name, p => p.Value);

                        foreach (var k in key)
                        { 
                            if(k.Key== "docs")
                            {
                                var tests = JsonConvert.DeserializeObject<JArray>(k.Value.ToString());
                                var data = k.Value.SelectToken("").Children().First();
                                var test = data.SelectToken("").Children().OfType<JProperty>().ToDictionary(p => p.Name, p => p.Value);
                                foreach (var t in test)
                                {
                                    if (t.Key == "url")
                                    {
                                        model.Source = t.Value.ToString();
                                    }
                                    else if (t.Key=="title")
                                    {
                                        model.Title = t.Value.ToString();
                                    }
                                }
                            }
                        }
                    }
                }
                return new JsonResult(model);
            }
        }
    }
}
[HttpGet("[Action]")]
public string test() 
{
   //for easy testing,I just read your json file and return string
    var jsonstring = System.IO.File.ReadAllText("C:\\test.json");
    return jsonstring;
}

推荐阅读