C# 我在GetProductAsync中反序列化JSON对象是否错误?
当我运行这段代码时,会收到以下错误消息: 无法将当前JSON数组(例如[1,2,3])反序列化为类型“HttpClientSample.Product”,因为该类型需要一个JSON对象(例如{“name”:“value”})才能正确反序列化。 要修复此错误,请将JSON更改为JSON对象(例如{“name”:“value”}),或将反序列化类型更改为数组或实现可从JSON数组反序列化的集合接口(例如ICollection、IList)类似列表的类型。还可以将JsonArrayAttribute添加到类型中,以强制它从JSON数组反序列化 我想我告诉我的客户返回一个JSON……我需要转换我的响应(JsonConvert.DeserializeObject)吗?如果有,请列出清单 使用邮递员的典型反应是:C# 我在GetProductAsync中反序列化JSON对象是否错误?,c#,json,async-await,httpclient,C#,Json,Async Await,Httpclient,当我运行这段代码时,会收到以下错误消息: 无法将当前JSON数组(例如[1,2,3])反序列化为类型“HttpClientSample.Product”,因为该类型需要一个JSON对象(例如{“name”:“value”})才能正确反序列化。 要修复此错误,请将JSON更改为JSON对象(例如{“name”:“value”}),或将反序列化类型更改为数组或实现可从JSON数组反序列化的集合接口(例如ICollection、IList)类似列表的类型。还可以将JsonArrayAttribute添
[
{
"id": "1",
"name": "test",
"inactive": false
},
{
"id": "2",
"name": "test2",
"inactive": false
}
]
多谢各位
using Newtonsoft.Json;
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace HttpClientSample
{
public class Product
{
public string id { get; set; }
public string name { get; set; }
public bool inactive { get; set; }
}
class Program
{
static HttpClient client = new HttpClient();
static async Task<Product> GetProductAsync(string path)
{
Product product = null;
HttpResponseMessage response = await client.GetAsync(path);
if (response.IsSuccessStatusCode)
{
product = await response.Content.ReadAsAsync<Product>();
Console.WriteLine("{0}\t${1}\t{2}", product.id, product.name, product.inactive);
}
return product;
}
static void Main()
{
// RunAsync().GetAwaiter().GetResult();
RunAsync().Wait();
}
static async Task RunAsync()
{
// Update port # in the following line.
var byteArray = Encoding.ASCII.GetBytes("user:pass");
client.BaseAddress = new Uri("https://localhost:51075/api/products");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
try
{
Product product = new Product();
// Get the product
product = await GetProductAsync("https://localhost:51075/api/products");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
}
}
使用Newtonsoft.Json;
使用制度;
Net系统;
使用System.Net.Http;
使用System.Net.Http.Header;
使用系统文本;
使用System.Threading.Tasks;
命名空间HttpClientSample
{
公共类产品
{
公共字符串id{get;set;}
公共字符串名称{get;set;}
公共bool非活动{get;set;}
}
班级计划
{
静态HttpClient=新HttpClient();
静态异步任务GetProductAsync(字符串路径)
{
Product=null;
HttpResponseMessage response=wait client.GetAsync(路径);
if(响应。IsSuccessStatusCode)
{
product=wait response.Content.ReadAsAsync();
Console.WriteLine(“{0}\t${1}\t{2}”,product.id,product.name,product.inactive);
}
退货产品;
}
静态void Main()
{
//RunAsync().GetAwaiter().GetResult();
RunAsync().Wait();
}
静态异步任务RunAsync()
{
//在下一行中更新端口#。
var bytearay=Encoding.ASCII.GetBytes(“user:pass”);
client.BaseAddress=新Uri(“https://localhost:51075/api/products");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(新的MediaTypeWithQualityHeaderValue(“应用程序/json”);
client.DefaultRequestHeaders.Authorization=new System.Net.Http.Headers.AuthenticationHeaderValue(“Basic”,Convert.ToBase64String(byteArray));
ServicePointManager.ServerCertificateValidationCallback=委托{return true;};
尝试
{
产品=新产品();
//获取产品
产品=等待GetProductAsync(“https://localhost:51075/api/products");
}
捕获(例外e)
{
控制台写入线(e.Message);
}
Console.ReadLine();
}
}
}您的问题似乎是JSON数组的格式不正确。为了让我的例子起作用,我必须在}后面加一个逗号,用答案更新:) GetResponseAsync函数:
public static async Task<SetupWebApiResponse> GetResponseAsync(string
endpoint)
{
string result = "";
HttpResponseMessage response = await client.GetAsync(endpoint);
if (response.IsSuccessStatusCode)
{
HttpContent content = response.Content;
result = await content.ReadAsStringAsync();
}
return new SetupWebApiResponse(response.StatusCode, result);
}
这取决于您决定获取错误是否是代码的正确行为(我们如何找出您的实际期望值?)。。。你确定标题中的问题正是你需要知道的吗?你“典型回答”中的方括号表示(产品项目)列表。因此,您需要相应地更改ReadAsAsync方法的泛型参数。这只是一个问题,您需要的是单个
产品
,还是一组产品
。反序列化您所期望的内容。看起来您期望的是一个只有一个元素的数组,它仍然需要反序列化为数组或其他集合。错误似乎很简单。你不明白什么?更新了我期望的响应示例。你认为这个建议实际上如何适用于所描述的问题?我忘记了数组部分。。。修正了。你没有解释为什么这是必要的。为什么不使用问题已经描述过的类呢?不,它不是一个格式错误的JSON数组。这个问题清楚地描述了错误。@fazlook1,我想提供更多帮助,但我必须重新创建一个模仿您的设置的REST服务:(,我现在没有时间。JSON是一个非常痛苦的问题,当我在JSON中遇到这些问题时,我最终会使用XML REST…哈哈,哦,顺便说一句,如果您能将其放入一个数组中,您可以这样做。ToList(),如果JsonConvert更喜欢的话。
public static async Task<SetupWebApiResponse> GetResponseAsync(string
endpoint)
{
string result = "";
HttpResponseMessage response = await client.GetAsync(endpoint);
if (response.IsSuccessStatusCode)
{
HttpContent content = response.Content;
result = await content.ReadAsStringAsync();
}
return new SetupWebApiResponse(response.StatusCode, result);
}
public class SetupWebApiResponse
{
public SetupWebApiResponse() { }
public SetupWebApiResponse(int statusCode, object responseBody)
{
this.StatusCode = statusCode;
this.ResponseBody = responseBody;
}
public SetupWebApiResponse(HttpStatusCode statusCode, object responseBody)
: this((int)statusCode, responseBody)
{
}
/// <summary>
/// Gets or sets the HTTP status code of the response
/// </summary>
public int StatusCode { get; set; }
/// <summary>
/// Gets or sets the response body content
/// </summary>
public object ResponseBody { get; set; }
}
public class SetupWebAPI
{
static string User;
static string Password;
static string Endpoint;
static object Content;
static SetupWebApiResponse apiResponse;
public static SetupWebApiResponse GetResponseInStringFormat(string user, string password, string endpoint)
{
User = user;
Password = password;
Endpoint = endpoint;
ExecuteResponse().Wait();
return apiResponse;
}
private static async Task ExecuteResponse()
{
SetupWebAPIAsync.SetAPIAuthentication(User, Password);
apiResponse = await SetupWebAPIAsync.GetResponseAsync(Endpoint);
}