如何解决将 json 反序列化为我的 C# 对象给出错误
我得到这样的 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,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 中,Users
JArray 位于 JObject 内,因此要转换您的 JSON 字符串,您需要在 List<User>
类中使用 RootObject
,如
public class User
{
public string id { get; set; }
public string name { get; set; }
public List<string> permissions { get; set; }
}
public class Root
{
public List<User> users { get; set; }
}
反序列化,
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(result);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。