Search code examples
c#arraysjsonapijson.net

Deserialize array from JSON in C#


So I am trying to deserialize an array from JSON into a C# class using Newtonsoft. I have seen tutorials and other questions on this, but I am running into problems as the array I want to get is not at the top level of the JSON. The JSON is structured like this, where I want to extract the "data" array and deserialize it:

 "success": true,
  "data": [
    {      
      "key": "americanfootball_nfl",
      "active": true,
      "group": "American Football",
      "details": "US Football",
      "title": "NFL",
      "has_outrights": false
    },
    {
      "key": "aussierules_afl",
      "active": true,
      "group": "Aussie Rules",
      "details": "Aussie Football",
      "title": "AFL",
      "has_outrights": false
    },
    {
      "key": "basketball_euroleague",
      "active": true,
      "group": "Basketball",
      "details": "Basketball Euroleague",
      "title": "Basketball Euroleague",
      "has_outrights": false
    }
]}

I know that I first need to extract the data object from the JSON, and then parse that, but I am not too sure how. I have this class to deserialize the JSON:

public class SportsModel
    {       
        public bool Success { get; set; }
        public string Data { get; set; }       
    }

    public class SportsData
    {
        public string Key { get; set; }
        public bool Active { get; set; }
        public string Group { get; set; }
        public string Details { get; set; }
        public string Title { get; set; }
        public bool HasOutrights { get; set; }
    }

And currently get the top level of the data using this:

SportsModel data = JsonConvert.DeserializeObject<SportsModel>(response);

I want to put the JSON array data into a list object, so that I can access it all


Solution

  • You only need to fix this part to make the serializer understand you're deserializing the Data field into a type of SportsData and not a string.

    public class SportsModel
    {
       public bool Success { get; set; } 
       public List<SportsData> Data { get; set; } 
    }
    

    Update To get data into a list, I would assume you are referring to something of this nature

    SportsModel result = JsonConvert.DeserializeObject<SportsModel>(response);
    var sportsDataList = result.Data;