c# - 反序列化 JSON 并返回 C# 中的值?
问题描述
我正在开发 Xamarin App,我正在尝试从服务器获取 Json 数据,并且运行良好。
但是,现在我只想阅读/查看"invitation"的值。
json值:
{"invitation":"http://example.com?c_i=eyJsYWJlbCI6Iklzc3VlciIsImltYWdlVXJsIjpudWxsLCJzZXJ2aWNlRW5kcG9pbnQiOiJodHRwOi8vNTIuNzcuMjI4LjIzNDo3MDAwIiwicm91dGluZ0tleXMiOlsiSE51N0x6MkxoZktONEZEMzM2cWdDNWticWI0dTZWRkt2NERaano4YWc1eHQiXSwicmVjaXBpZW50S2V5cyI6WyI3Sm1MMVhOSHRqSHB2WW1KS3d0ZXM2djltNk5yVUJoZW1ON3J6TnZLcGN0SyJdLCJAaWQiOiIzZjgyNWRkZC0zNjNhLTQ2YzEtYTAxNi0xMjAwY2FhZjRkNTkiLCJAdHlwZSI6ImRpZDpzb3Y6QnpDYnNOWWhNcmpIaXFaRFRVQVNIZztzcGVjL2Nvbm5lY3Rpb25zLzEuMC9pbnZpdGF0aW9uIn0="}
我收到此错误...不知道为什么?
错误信息:
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Osma.Mobile.App.ViewModels.Index.IndexViewModel+RootObject]' 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.
Path 'invitation', line 1, position 14.'
我写的代码......
班级:
public class ConnectionJson
{
public string Invitation { get; set; }
}
public class RootObject
{
public List<ConnectionJson> ConnectionsJson { get; set; }
}
主要代码:
public async Task<List<RootObject>> ConnectionInvitationJson()
{
HttpClient hTTPClient = new HttpClient();
Uri uri = new Uri(string.Format("http://example.com/Connections/CreateInvitationJson"));
HttpResponseMessage response = await hTTPClient.GetAsync(uri);
string content = await response.Content.ReadAsStringAsync();
var Items = JsonConvert.DeserializeObject<List<RootObject>>(content);
await DialogService.AlertAsync(Items.ToString(), "Connection Invitation Json", "Ok");
return Items;
}
解决方案
Your Json is just a single object. Update the code as below
var json = JsonConvert.DeserializeObject<ConnectionJson>(content);
After updating the code you can modify the logic as below if you don't want to change the classes structure
var Items = new List<RootObject> { new List<ConnectionJson> { json }};
推荐阅读
- angular - Angular 4 - 如何在具有不同布局(页眉和页脚)的页面之间路由?
- aem - 在 AEM Communities 中使用扩展的 Jouranl 组件时无法保存数据
- c - 我可以在scanf中放置一个for循环吗?
- python - 如何让 mpi4py 运行?
- c - 在C中释放文件写锁?
- delphi - 如何使用 WSDL Importer 以编程方式提供凭据
- javascript - 需要帮助使用 jquery 选择器来选择特定元素
- python - 使用 requests_html 时无法按预期提取结果
- c# - 成功提交具有浮动类型实体后如何重置表单?
- javascript - Eslint 没有检测到 React 组件的定义属性类型