首页 > 解决方案 > 反序列化 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;
        }

标签: c#.netjsonxamarinserialization

解决方案


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 }};

推荐阅读