0

I'm making a class that holds data that is converted from a JSON file. It normally works when I use JsonConvert.DeserializeObject<OverallData>(text);, but when I try to make the class implement the IEnumerable interface, suddenly I got an error when converting. Why would implementing the interface cause the object to not get created correctly?

Error: "Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'CoronaScraper.OverallData' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.\r\nTo fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.\r\nPath 'lastUpdatedDate', line 1, position 19."

public class OverallData// : IEnumerable<IllinoisTestingResults>
    {
        [JsonProperty("lastUpdatedDate")]
        private LastUpdatedDate LastUpdatedDate { get; set; }
        public DateTime UpdatedDate => LastUpdatedDate.DateTime;
        [JsonProperty("state_testing_results")]
        public List<IllinoisTestingResults> StateTestingResults { get; set; } = new ();
        //#region Implementation of IEnumerable

        //public IEnumerator<IllinoisTestingResults> GetEnumerator()
        //{
        //    foreach (IllinoisTestingResults result in StateTestingResults)
        //    {
        //        yield return result;
        //    }
        //}

        //IEnumerator IEnumerable.GetEnumerator()
        //{
        //    return GetEnumerator();
        //}

        //#endregion

        public IllinoisTestingResults this[int index] => StateTestingResults[index];
        public IllinoisTestingResults this[DateTime date]
        {
            get
            {
                foreach (IllinoisTestingResults result in StateTestingResults)
                {
                    if (result.TestDate == date)
                    {
                        return result;
                    }
                }
                return null;
            }
        }
    }
dbc
  • 104,963
  • 20
  • 228
  • 340
lwashington27
  • 320
  • 2
  • 14
  • You can write a cast converter and use `JsonConverter` attribute as you appear to be using Newtonsoft.Json – zaitsman Sep 16 '21 at 01:28
  • 1
    Mark `OverallData` with `[JsonObject]` as shown in [this answer](https://stackoverflow.com/a/19087883/3744182) by [Brian Rogers](https://stackoverflow.com/users/10263/brian-rogers) to [Deserialize to IEnumerable class using Newtonsoft Json.Net](https://stackoverflow.com/q/19080326/3744182) and Json.NET will serialize its properties as before. – dbc Oct 09 '21 at 06:10

0 Answers0