【发布时间】:2021-08-02 16:24:16
【问题描述】:
我得到这样的 JSON 并希望将其反序列化为我的 C# 对象。但这最终会导致无法反序列化的错误。我可以得到帮助来解决这个问题吗?
public class UserDto {
public string Id { get; set; }
public string Name { get; set; }
public List<string> Permissions { get; set; }
}
上面是绑定API输出的模型对象
HttpResponseMessage response = await client.GetAsync($"/users");
if (!response.IsSuccessStatusCode || response.Content == null) {
return null;
}
string result = await response.Content.ReadAsStringAsync();
UserDto users = await response.Content.ReadAsJsonAsync<UserDto>();
List<UserDto> x2 = JsonConvert.DeserializeObject<List<UserDto>>(result);
上面的getasync 方法给了我下面的结果,我正在尝试将它反序列化为对象。
{
"users": [{
"id": "1",
"name": "ttest",
"permissions": [
"add",
"edit",
"delete"
]
}]
}
错误:
Cannot deserialize the current JSON object (e.g. {"name":"value"})
into type 'System.Collections.Generic.List`1[****.Models.UserDto]'
because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3])
or change the deserialized type so that it is a normal .NET type
(e.g. not a primitive type like integer, not a collection type like an
array or List<T>) that can be deserialized from a JSON object.
JsonObjectAttribute can also be added to the type to force it to
deserialize from a JSON object.
我得到这样的 JSON 并希望将其反序列化为我的 C# 对象。但这最终会导致无法反序列化的错误。我可以得到帮助来解决这个问题吗?
【问题讨论】:
-
首先,不能把内容读两遍。如果您想将其作为字符串和 JSON 读取,则需要先将其复制到内存流。但我建议完全放弃这个字符串。从一开始就将其读取为 JSON,您只需要与 JSON 结构相对应的正确 DTO。
标签: c# asp.net-mvc asp.net-core jsonserializer