如何解决要反序列化JSON并在C#中返回值?
我正在使用Xamarin App,正在尝试从服务器获取Json数据,并且工作正常。
但是,现在我只想阅读/查看“邀请” 的值。
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,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;
}
解决方法
您的Json只是一个对象。更新代码如下
var json = JsonConvert.DeserializeObject<ConnectionJson>(content);
更新代码后,如果您不想更改类结构,则可以修改以下逻辑
var Items = new List<RootObject> { new List<ConnectionJson> { json }};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。