且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Api 响应作为列表/从 api 响应中获取所有数据

更新时间:2022-10-17 17:24:21

如何检索从实际 API 获得的全部响应.

如果你想返回所有实际的 api 响应,那么只需使用以下代码:

[HttpGet("[action]/{query}")]公共异步任务产品(字符串查询){var model = new SearchModel();使用 (var client = new HttpClient()){尝试{client.BaseAddress = new Uri("http://xx.xx.xxx.xx:8080");var response = await client.GetAsync($"/abc/xxx/select?q=title%3A%22{query}%22");response.EnsureSuccessStatusCode();var stringResult = await response.Content.ReadAsStringAsync();var root = (JObject)JsonConvert.DeserializeObject(stringResult);返回新的 JsonResult(root);}catch (InvalidOperationException httpreq){}}返回确定()}

如果您只想从实际响应中返回 List,则不应使用 var data = k.Value.SelectToken("").Children().First(); 只会检索 docs 数组的第一个元素.

尝试 foreach k.Value.SelectToken("").Children() 并返回 List 而不是 SearchModel,参考

[HttpGet("[action]/{query}")]公共异步任务产品(字符串查询){//初始化一个列表搜索模型var modelList = new List();使用 (var client = new HttpClient()){尝试{client.BaseAddress = new Uri("http://xx.xx.xxx.xx:8080");var response = await client.GetAsync($"/abc/xxx/select?q=title%3A%22{query}%22");response.EnsureSuccessStatusCode();var stringResult = await response.Content.ReadAsStringAsync();var root = (JObject)JsonConvert.DeserializeObject(stringResult);var items = root.SelectToken("").Children().OfType().ToDictionary(p => p.Name, p => p.Value);foreach (var item in items){if (item.Key == "response"){var key = item.Value.SelectToken("").OfType().ToDictionary(p => p.Name, p => p.Value);foreach (var k in key){if (k.Key == "docs"){//删除.First()var arrayData = k.Value.SelectToken("").Children();foreach(arrayData 中的 var 数据){var model = new SearchModel();var test = data.SelectToken("").Children().OfType().ToDictionary(p => p.Name, p => p.Value).ToList();foreach(测试中的var t){if (t.Key == "url"){model.Source = t.Value.ToString();}else if (t.Key == "title"){模型.标题 = t.Value.ToString();}}模型列表.添加(模型);}}}}}返回新的 JsonResult(modelList);}catch (InvalidOperationException httpreq){}}返回确定();}

I am new to .netcore mvc architecture. I am trying to consume the api data response, So far I have successfully fetched the data, but the problem I am facing is when the api response/result is more than one. Forexample if the actuall api response is the following

  "responseHeader":{
    "status":0,
    "QTime":0,
    "params":{
      "q":"title:\"A\""}},
  "response":{"numFound":3,"start":0,"docs":[
      {
        "date":"1970-01-01T00:00:00Z",
        "tstamp":"2019-11-22T12:22:31.698Z",
        "digest":"e23d679991d80d832504e7395d139fe4",
        "contentLength":"25476",
        "boost":0.0,

       "title":["emb- A1]
        "url":"https://www.example.com/a/b/c0/"},
{
        "date":"1970-01-01T00:00:00Z",
        "tstamp":"2019-11-22T12:22:31.698Z",
        "digest":"e23d679991d80d832504e7395d139fe4",
        "contentLength":"25476",
        "boost":0.0,
   "title":["emb - A2]
        "url":"https://www.example.com/a/b/c1/"
},
{
        "date":"1970-01-01T00:00:00Z",
        "tstamp":"2019-11-22T12:22:31.698Z",
        "digest":"e23d679991d80d832504e7395d139fe4",
        "contentLength":"25476",
        "boost":0.0,
   "title":["emb - A3]
        "url":"https://www.example.com/a/b/c2/"
}

I am only getting

{"title":"[\r\n  \"emb- A1","source":"https://www.example.com/a/b/c0/"}

instead of having all the response data.

My Code is below. Model SearchModel.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

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

    }
}


Controller EngineController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using searchEngineTesting.Models;

namespace searchEngineTesting.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class EngineController : ControllerBase {


        [HttpGet("[action]/{query}")]
        public async Task<IActionResult> Product(string query)
        {
            var model = new SearchModel();
            using (var client = new HttpClient())
            {
                try
                {
                    client.BaseAddress = new Uri("http://xx.xx.xxx.xx:8080");
                    var response = await client.GetAsync($"/abc/xxx/select?q=title%3A%22{query}%22");
                    response.EnsureSuccessStatusCode();
                    var stringResult = await response.Content.ReadAsStringAsync();
                    var root = (JObject)JsonConvert.DeserializeObject(stringResult);
                    //var details = JsonConvert.DeserializeObject<SearchModel>(stringResult);
                    var items = root.SelectToken("").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).ToList();
                                    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);

                }
                catch (InvalidOperationException httpreq) {
                    return BadRequest("Sorry: There are no results for your query");
                }
            }
        }



    }
}

How can I retrieve whole of the response I am getting from actual API.

Please help..!

How can I retrieve whole of the response I am getting from actual API.

If you want to return all the actual api response,then just use below code:

[HttpGet("[action]/{query}")]
public async Task<IActionResult> Product(string query)
    {
        var model = new SearchModel();
        using (var client = new HttpClient())
        {
            try
            {
                client.BaseAddress = new Uri("http://xx.xx.xxx.xx:8080");
                var response = await client.GetAsync($"/abc/xxx/select?q=title%3A%22{query}%22");
                response.EnsureSuccessStatusCode();
                var stringResult = await response.Content.ReadAsStringAsync();
                var root = (JObject)JsonConvert.DeserializeObject(stringResult);

                return new JsonResult(root);
            }
            catch (InvalidOperationException httpreq)
            {

            }
        }
        return Ok()
     }

If you would like to just return List<SearchModel> from the actual response,you should not use var data = k.Value.SelectToken("").Children().First(); which will only retrieve the first element of docs array.

Try to foreach k.Value.SelectToken("").Children() and return List<SearchModel> instead of a SearchModel,refer to

[HttpGet("[action]/{query}")]
public async Task<IActionResult> Product(string query)
    {
        //initialize a list SearchModel
        var modelList = new List<SearchModel>();

        using (var client = new HttpClient())
        {
            try
            {
                client.BaseAddress = new Uri("http://xx.xx.xxx.xx:8080");
                var response = await client.GetAsync($"/abc/xxx/select?q=title%3A%22{query}%22");
                response.EnsureSuccessStatusCode();
                var stringResult = await response.Content.ReadAsStringAsync();
                var root = (JObject)JsonConvert.DeserializeObject(stringResult);

                var items = root.SelectToken("").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")
                            {
                                //remove .First()
                                var arrayData = k.Value.SelectToken("").Children();
                                foreach(var data in arrayData)
                                {
                                    var model = new SearchModel();
                                    var test = data.SelectToken("").Children().OfType<JProperty>().ToDictionary(p => p.Name, p => p.Value).ToList();
                                    foreach (var t in test)
                                    {
                                        if (t.Key == "url")
                                        {
                                            model.Source = t.Value.ToString();
                                        }
                                        else if (t.Key == "title")
                                        {
                                            model.Title = t.Value.ToString();
                                        }
                                    }

                                    modelList.Add(model);
                                }

                            }
                        }
                    }
                }

                return new JsonResult(modelList);

            }
            catch (InvalidOperationException httpreq)
            {

            }
        }

        return Ok();
    }