.net-core - 使用 .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
获取和。title
url
解决方案
您可以像下面这样获取 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;
}
推荐阅读
- javascript - 当 websocket 服务器在线时 button.onclick 不起作用
- xaml - 如何在 ListView 上使用 CanContentRenderOutsideBounds
- python - Python - Mysqldb 安装错误 [错误:命令错误退出状态为 1:]
- python - 使用 Reticulate 在 R Markdown 中的 Python 打印查询
- python - 使用 AWK 更正大型数据集?
- python - 需要帮助了解如何使用 plotly 绘制 3d 曲面图
- reactjs - Bootstrap-table 使用 Firebase 实时数据库显示“No matching records found”和 bootstrap-table 中的记录
- android - 为什么我的代码在转换为 smali 时会抛出此错误?
- javascript - TinyMCE 为每页导出带有页脚的 pdf
- c++ - 如何计算方向矢量以避开附近的代理