【问题标题】:JSON Deserialization C#JSON反序列化C#
【发布时间】:2013-03-02 05:16:29
【问题描述】:

我正在尝试解析一些我从 RottenTomatoes 中检索到的 JSON 格式的信息

{
    "cast": [
        {
            "id": "162655641",
            "name": "Tom Hanks",
            "characters": [
                "Woody"
            ]
        },
        {
            "id": "162655909",
            "name": "Tim Allen",
            "characters": [
                "Buzz Lightyear"
            ]
        },
        {
            "id": "162655020",
            "name": "Joan Cusack",
            "characters": [
                "Jessie the Cowgirl"
            ]
        },
        {
            "id": "162672460",
            "name": "Ned Beatty",
            "characters": [
                "Lots-o'-Huggin' Bear",
                "Lotso"
            ]
        },
        {
            "id": "162657445",
            "name": "Richard Kind",
            "characters": [
                "Bookworm"
            ]
        },
        {
            "id": "162654813",
            "name": "Erik von Detten",
            "characters": [
                "Sid"
            ]
        },
        {
            "id": "770713272",
            "name": "James Anthony Cotton",
            "characters": []
        }
    ],
    "links": {
        "rel": "http://api.rottentomatoes.com/api/public/v1.0/movies/770672122.json"
    }
}

我只是想让这段代码工作,但我得到一个 InvalidOperationException 和这个错误 “数组的反序列化不支持类型 'System.String'。”

这是我在 main 中的代码

string json = File.ReadAllText("json.txt");

CastInfo castMember = new JavaScriptSerializer().Deserialize<CastInfo>(json);

这是我的课程

public class CastInfo
{
    public List<CustomCastInfo> cast { get; set; }
}
public class CustomCastInfo
{
    public string id { get; set; }
    public string name { get; set; }
    public List<string> characters { get; set; }

}

还有建议?而且我意识到我需要对底部的“链接”做一些事情,但即使我删除它仍然不起作用。

【问题讨论】:

    标签: c# json deserialization javascriptserializer


    【解决方案1】:

    我刚刚尝试使用您提供的 json 运行它,它运行良好。

    using System.Collections.Generic;
    using System.IO;
    using System.Web.Script.Serialization;
    
    namespace JsonDeserialization
    {
        class Program
        {
            static void Main(string[] args)
            {
                string json = File.ReadAllText("json.txt");
    
                CastInfo castMember = new JavaScriptSerializer().Deserialize<CastInfo>(json);
            }
        }
    
        public class CastInfo
        {
            public List<CustomCastInfo> cast { get; set; }
        }
        public class CustomCastInfo
        {
            public string id { get; set; }
            public string name { get; set; }
            public List<string> characters { get; set; }
    
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2012-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-06
      相关资源
      最近更新 更多