Arrays 将从外部Url返回的JSON反序列化到对象中
好的,我的json返回字符串如下所示:Arrays 将从外部Url返回的JSON反序列化到对象中,arrays,json,asp.net-mvc,asp.net-core,serialization,Arrays,Json,Asp.net Mvc,Asp.net Core,Serialization,好的,我的json返回字符串如下所示: { "categories": [ { "id": "1", "category": "cat-1" }, { "id": "2", "category": "cat-2" }, { "id": "3", "category": "cat-3" } ] } var
{
"categories": [
{
"id": "1",
"category": "cat-1"
},
{
"id": "2",
"category": "cat-2"
},
{
"id": "3",
"category": "cat-3"
}
]
}
var result = await response.Content.ReadAsAsync<CategoryViewModelContainer>();
此返回类别列表将用作我的引导导航菜单中的下拉列表,因此我希望使用尽可能少的调用量,因为如果不需要的话,它可能不会经常更改,以至于在每次页面刷新时都需要全部更改
如何写出要绑定到此字符串的模型/视图模型?然后,我想使用类似这样的方法来返回CategoryViewModel的列表,我可以从中进行迭代
public async Task<IEnumerable<CategoryViewModel>> GetCategoryList () {
HttpResponseMessage response = await httpClient.GetAsync ("/categories");
response.EnsureSuccessStatusCode ();
var result = await response.Content
.ReadAsAsync<IEnumerable<CategoryViewModel>> ();
return result;
}
public异步任务GetCategoryList(){
HttpResponseMessage response=等待httpClient.GetAsync(“/categories”);
response.EnsureSuccessStatusCode();
var result=wait response.Content
.ReadAsAsync();
返回结果;
}
您拥有的JSON模型需要一个容器类,例如:
public class CategoryViewModelContainer
{
public IEnumerable<CategoryViewModel> Categories { get; set; }
}
//Assuming your category view model looks like this:
public class CategoryViewModel
{
public int Id { get; set; }
public string Category { get; set; }
}
快速响应和逻辑解释,我将尝试使这项工作。我对重新开始工作有些生疏,非常感谢你的帮助。我会带着结果回来的。
foreach(var categoryModel in result.Categories)
{
var categoryName = categoryModel.Category;
}