繁体   English   中英

数组反序列化不支持该类

[英]Class is not supported for deserialization of an array

我收到一个错误:

System.InvalidOperationException:数组反序列化不支持类型“ VK.Response”。

我得到的JSON看起来像:

{“响应”:[{“ id”:269058571,“ first_name”:“ Name”,“ last_name”:“ LastName”,“ photo_50”:“ http://cs624717.vk.me/v624717571/21718/X8。 jpg“}]}

我的方法是:

 private void getFriendInfo()
    {
        string method = "users.get";
        string param = "user_ids=269058571&fields=photo_50";
        string url = "https://api.vk.com/method/" + method + "?" + param + "&v=5.31&access_token=" + key + "";

        WebClient client = new WebClient();

        string json = client.DownloadString(url);
        JavaScriptSerializer json_serializer = new JavaScriptSerializer();
        RootObject response = (RootObject)json_serializer.Deserialize(json, typeof(RootObject));
        for (int counter = 0; counter < response.response.items.Count; counter++)
        {
            pictureBox1.Load(response.response.items[counter].photo_50);
        }
    }

类:

      class Response
        {
            public int count { get; set; }
            public List<Item> items { get; set; }
        }

       class RootObject
       {
            public Response response { get; set; }
       }
       class Item
       {
            public string first_name { get; set; }
            public string last_name { get; set; }
            public string domain { get; set; }
            public string photo_50 { get; set; }
       }

尝试像这样声明您的“ RootObject”类:

class RootObject
       {
            public List<Response> response { get; set; }
       }

您的对象模型未与json对齐。 尝试一下(我现在使用的是Newtonsoft.Json,它是当今的标准JSON库,而不是带有.Net的库)。使用nuget包管理器来获取它... https://www.nuget.org/packages/ newtonsoft.json /

using System;
using System.Collections.Generic;
using Newtonsoft.Json;

public class Program
{
    public static void Main()
    {
        var json = "{\"response\":[{\"id\":269058571,\"first_name\":\"Name\",\"last_name\":\"LastName\",\"photo_50\":\"http://cs624717.vk.me/v624717571/21718/X8.jpg\"}]}";

        var obj = JsonConvert.DeserializeObject<RootObject>(json);

        foreach(var item in obj.response) {
            Console.WriteLine(item.first_name);
        }           
    }
}

class RootObject
{
    public List<Item> response { get; set; }
}
class Item
{
    public string first_name { get; set; }
    public string last_name { get; set; }
    public string domain { get; set; }
    public string photo_50 { get; set; }
}

实时示例: https//dotnetfiddle.net/WJwvm3

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM