【发布时间】:2021-02-21 03:00:23
【问题描述】:
我正在使用System.Text.Json 对我的JSON 进行反序列化,我知道Json.Net 并选择不使用它。
我正在使用返回字符串的System.Net.Http.HttpClient.GetStringAsync 方法向https://jsonplaceholder.typicode.com/ 发出请求。对请求的响应是一个 JSON 数组,其中填充了具有以下键的对象:userId、id、title 和 body。我正在使用Deserialize generic 方法对我的JSON 进行反序列化,其中Posts 是我的返回类型,response 是我的字符串。
通过捕获异常,我得到如下所示的错误。
我目前有
static readonly HttpClient client = new HttpClient();
static async Task Main(string[] args)
{
await GetPostAsync();
}
static async Task GetPostAsync()
{
client.BaseAddress = new Uri("https://jsonplaceholder.typicode.com/");
string location = "posts";
try
{
string response = await client.GetStringAsync(location);
Posts deserializedPosts = JsonSerializer.Deserialize<Posts>(response);
Console.WriteLine(deserializedPosts);
}
catch (System.Exception e)
{
Console.WriteLine(e);
}
}
class Posts
{
public int userId { get; set; }
public int id { get; set; }
public string title { get; set; }
public string body { get; set; }
}
我收到的错误
System.Text.Json.JsonException: The JSON value could not be converted to fugo.Program+Posts. Path: $ | LineNumber: 0 | BytePositionInLine: 1.
at System.Text.Json.ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(Type propertyType)
at System.Text.Json.JsonSerializer.HandleStartArray(JsonSerializerOptions options, Utf8JsonReader& reader, ReadStack& state)
at System.Text.Json.JsonSerializer.ReadCore(JsonSerializerOptions options, Utf8JsonReader& reader, ReadStack& readStack)
at System.Text.Json.JsonSerializer.ReadCore(Type returnType, JsonSerializerOptions options, Utf8JsonReader& reader)
at System.Text.Json.JsonSerializer.Deserialize(String json, Type returnType, JsonSerializerOptions options)
at System.Text.Json.JsonSerializer.Deserialize[TValue](String json, JsonSerializerOptions options)
at fugo.Program.GetPostAsync() in /home/kepler/PROJECTS/C-SHARP/fugo/Program.cs:line 27
【问题讨论】:
-
也许您可以发布一个有效负载示例。很多时候,这样的问题是由双重序列化或无效字符或其某种组合引起的。您可以发布通过网络发布的内容吗?
-
有效载荷是指响应吗?
-
@RossBush -- 在代码中:
https://jsonplaceholder.typicode.com/posts
标签: c# json dotnet-httpclient