简体   繁体   English

使用 asp.net web.api json 不起作用

[英]Consuming asp.net web.api json not working

I'm trying to consume my web api which returns JSON format from my asp.net mvc web application.我正在尝试使用我的 web api,它从我的 asp.net mvc web 应用程序返回 JSON 格式。 As my JSON format has root node (the way i filled with oledb dataset).因为我的 JSON 格式有根节点(我用 oledb 数据集填充的方式)。 I'm keep getting the following error.我不断收到以下错误。

Cannot deserialize the current JSON object (eg {"name":"value"}) into type 'System.Collections.Generic.List'1[FileAttributes]' because the type requires a JSON array (eg [1,2,3]) to deserialize correctly.无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型 'System.Collections.Generic.List'1[FileAttributes]',因为该类型需要 JSON 数组(例如 [1,2,3] ) 以正确反序列化。 To fix this error either change the JSON to a JSON array (eg [1,2,3]) or change the deserialized type so that it is a normal .NET type (eg not a primitive type like integer, not a collection type like an array or List<T> ) that can be deserialized from a JSON object.要修复此错误,请将 JSON 更改为 JSON 数组(例如 [1,2,3])或更改反序列化类型,使其成为普通的 .NET 类型(例如,不是像整数这样的原始类型,而不是像这样的集合类型)可以从 JSON 对象反序列化的数组或List<T> )。 JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. JsonObjectAttribute 也可以添加到类型中以强制它从 JSON 对象反序列化。 Path 'SearchData', line 1, position 14.路径“SearchData”,第 1 行,位置 14。

Here is the code sample这是代码示例

string Baseurl = "http://localhost:62602/";
client.BaseAddress = new Uri(Baseurl);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage Res = await client.GetAsync("api/FileSearch/?searchTerm=" + searchTerm );
if (Res.IsSuccessStatusCode)
{
    var fsResponse = Res.Content.ReadAsStringAsync().Result;
    List<FileAttributes> fileAttribultes = JsonConvert.DeserializeObject<List<FileAttributes>>(fsResponse);
}

And then following some ideas, I used JSON.Parse and SelectToken to remove root node, but this time the List<FileAttributes> returns data but with null values然后按照一些想法,我使用JSON.ParseSelectToken删除根节点,但这次List<FileAttributes>返回数据但值为空

JToken jtok = JObject.Parse(fsResponse).SelectToken("SearchData");
List<FileAttributes> fileAttribultes = JsonConvert.DeserializeObject<List<FileAttributes>>(fsResponse);

Here is my FileAttributes class这是我的 FileAttributes 类

public class FileAttributes
{
    public string Name { get; set; }
    public string Header { get; set; }
    public string Title { get; set; }
 }

I appreciate if anyone check whats wrong in the deserialization of JSON part with root node and whats the right way to do it?我很感激是否有人检查根节点的 JSON 部分反序列化有什么问题,以及正确的方法是什么?

Copied from POSTMAN output从 POSTMAN 输出复制

{ "SearchData": [ { "SYSTEM.NAME": "FILE NAME 1" , "SYSTEM.HEADER": "HEADER 1", "SYSTEM.TITLE": "TITLE 1", }, { "SYSTEM.NAME": "FILE NAME 1" , "SYSTEM.HEADER": "HEADER 1", "SYSTEM.TITLE": "TITLE 1", }, { "SYSTEM.NAME": "FILE NAME 1" , "SYSTEM.HEADER": "HEADER 1", "SYSTEM.TITLE": "TITLE 1", }] }

Based on the JSON the object model needs to be updated to match.基于 JSON,需要更新对象模型以匹配。 Which also need to include JsonProperty attribute to match up the JSON keys to the properties of the class.其中还需要包含JsonProperty属性以将 JSON 键与类的属性匹配。

public class FileAttributes {
    [JsonProperty("SYSTEM.NAME")]
    public string Name { get; set; }
    [JsonProperty("SYSTEM.HEADER")]
    public string Header { get; set; }
    [JsonProperty("SYSTEM.TITLE")]
    public string Title { get; set; }
}

public class RootObject {
    public IList<FileAttributes> SearchData { get; set; }
}

Then update the call to the service accordingly然后相应地更新对服务的调用

string Baseurl = "http://localhost:62602/";
client.BaseAddress = new Uri(Baseurl);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.GetAsync("api/FileSearch/?searchTerm=" + searchTerm );
if (response.IsSuccessStatusCode) {
    var json = await response.Content.ReadAsStringAsync();
    RootObject result = JsonConvert.DeserializeObject<RootObject>(json);
    var fileAttribultes = result.SearchData; 
    //...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 WEB API + ASP.NET尝试以json格式显示来自WEB.API的数据 - WEB API + ASP.NET trying to display data from WEB.API in json format ASP.NET Core Web.API中的拦截调用者语言 - Intercept caller language in ASP.NET Core Web.API 带有WEB.API和Castle Windsor容器的ASP.NET MVC - ASP.NET MVC with WEB.API and Castle Windsor container 我可以在Asp.net Web.API中的AppStart一次自定义RequestTelemetry属性吗? - Can I customize RequestTelemetry properties once at AppStart in Asp.net Web.API ASP.NET Core 2.1 Web.API更改应用程序见解的日志记录检测键 - ASP.NET Core 2.1 Web.API change application insights instrumentation key for logging ASP.NET web.api帮助页面不显示任何描述 - ASP.NET web.api Help Page does not show any description 如何在AuthorAttribute的ASP.NET Web.API MVC 5的IsAuthorized上获取Post参数 - How to get Post parameters on IsAuthorized of AuthorizeAttribute ASP.NET Web.API MVC 5 即使具有自定义验证属性,Asp.net Web.APi也会返回内置错误响应 - Asp.net Web.APi returns build in error response even with custom validation attribute 如何在ASP.NET Web.Api中运行后台任务? - How do I run Background Tasks in ASP.NET Web.Api? 使用Asp.net Webforms中的属性和web.api重定向到网页 - Redirect to a webpage using an attribute in Asp.net webforms with web.api
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM