【问题标题】:C# Webrequest json to object [closed]C# Webrequest json 到对象 [关闭]
【发布时间】:2018-03-27 13:09:38
【问题描述】:

我正在尝试将此 JSON 转换为类的对象,但我收到错误:“:”或“{”预期。

这是 JSON:

{"data":[{"id":"https:\/\/api.cognitive.microsoft.com\/api\/v7\/#WebPages.0", 
"name": "Epic Games' Fortnite",
"url": "https:\/\/www.epicgames.com\/fortnite\/", 
"about": [{"name": "Fortnite"}]]}

以下是课程:

class WebResult
{
    public string id { get; set; }
    public string name { get; set; }
    public string url { get; set; }
    public string[] about { get; set; }
}

class Results
{
    public List<WebResult> data { get; set; }
}

错误来了:

Results result = new JavaScriptSerializer().Deserialize<Results>(json);

【问题讨论】:

    标签: c# .net json deserialization javascriptserializer


    【解决方案1】:

    您的 json 无效。应该是:

    var json = {"data":[{"id":"https:\/\/api.cognitive.microsoft.com\/api\/v7\/#WebPages.0", 
    "name": "Epic Games' Fortnite",
    "url": "https:\/\/www.epicgames.com\/fortnite\/", 
    "about": [{"name": "Fortnite"}]}]}
    

    你的班级也应该有一个 About 班级:

    public class Results
    {
        public List<WebResult> Data { get; set; }
    }
    public class WebResult
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public string Url { get; set; }
        public List<About> About { get; set; }
    }
    public class About
    {
        public string Name { get; set; }
    }
    

    要反序列化,您可以执行以下操作:

    var deserializer = new JavaScriptSerializer();
    var result = deserializer.Deserialize<Results>(json);
    

    【讨论】:

    • 谢谢!工作得很好
    【解决方案2】:

    您必须关闭data 表中的第一个对象。如错误消息中所述,关闭about 表后缺少关闭}

    {
        "data":
        [
            {
                "id":"https://api.cognitive.microsoft.com/api/v7/#WebPages.0",
                "name":"Epic Games' Fortnite",
                "url":"https://www.epicgames.com/fortnite/",
                "about":[ { "name":"Fortnite" } ]
            }  <-- missing
        ]
    }
    

    您可以使用在线 json 解析器 (like this one) 快速解决语法错误。

    您的 C# 模型似乎对此 json 无效。要使用 json 创建 C# 类,请查看 quicktype

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-09
      • 2018-10-03
      • 1970-01-01
      • 1970-01-01
      • 2012-03-07
      • 1970-01-01
      • 2013-07-08
      • 2016-01-26
      相关资源
      最近更新 更多