Search code examples
c#jsonjson-deserialization

Deserialize Json into member class of a class


I have the following Json snippet:

{
  "lastUpdated": "2020-08-10T02:59:18+00:00",
  "providerName": "Some Provider",
  "language": "en-US",
  "movies": [
    {
    }
   ]
}

And these proposed class definitions:

[Serializable]

    public class JfoRoot
    {
        public JfoRoot()
        {
        }
    
        public string lastUpdated { get; set; }

        public string providerName { get; set; }

        public string language { get; set; }

    }

[Serializable]
    public class JsonFeedObject
    {        
        public JsonFeedObject()
        {
        }
        
        public JfoRoot jforoot { get; set; }
        
        public MovieObject[] movies { get; set; }
    }    

I'd like to deserialize the Json using:

jfo = JsonConvert.DeserializeObject<JsonFeedObject>(File.ReadAllText(path), jsonSerializerSettings);

Using the above, I'd like to deserialize the first three Json fields into the JfoRoot class. I tried using several approaches that included using [JsonConstructor] and providing a JsonConverter after reading the post Using Newtonsoft.Json with nested custom classes.

Nothing worked. The JfoRoot class was 'null' after every attempt I made. I feel I'm missing something obvious. Or, maybe this can't be done. Can someone shed some light if this is at all possible?


Solution

  • I was able to resolve this with a redesign of the classes I use. Rather than using:

    [Serializable]
        public class JsonFeedObject
        {        
            public JsonFeedObject()
            {
            }
            
            public JfoRoot jforoot { get; set; }
            
            public MovieObject[] movies { get; set; }
        }    
    

    I switched to:

    public class JsonFeedObject : JfoRoot
    

    It's such a simple change and it works to provide all deserialized fields.