Search code examples
c#.netjsondeserializationjavascriptserializer

C# Webrequest json to object


I'm trying to convert this JSON to an object of a class but I get the error: ":" or "{" expected.

This is the 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"}]]}

Here are the classes:

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

Here comes the error:

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

Solution

  • Your json is invalid. It should be:

    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"}]}]}
    

    Also your class should have an About class:

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

    To deserialize, you can do the following:

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