我试图将此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);
答案 0 :(得分:1)
您必须关闭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。
答案 1 :(得分: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"}]}]}
此外,您的班级应该有一个关于班级:
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);