I'm trying to deserialize a JSON API response into a mostly defined object, but it has a section that is dynamic. Is there a good way to handle this in dotnet core. I found answers that wanted me to define the root object as dynamic and then parse or deserialize into that, but I'd like to keep my root object as defined and just the child part as dynamic.
Here's the examples I found on stackoverflow that didn't fit what I was looking for:
dynamic d = JObject.Parse("{number:1000, str:'string', array: [1,2,3,4,5,6]}");
or
var product = new { Name = "", Price = 0 };
dynamic jsonResponse = JsonConvert.Deserialize(json, product.GetType());
or
dynamic jsonResponse = JsonConvert.DeserializeObject(json);
Console.WriteLine(jsonResponse["message"]);
What I have for class/data model definitions:
public class RootObject
{
public int Id { get; set; }
public DefinedData DefinedData { get; set; }
public DynamicData DynamicData { get; set; } // This one is dynamic
public DateTime DateCreated { get; set; }
public DateTime LastUpdated { get; set; }
public bool Enabled { get; set; }
}
The DefinedData section of the JSON is defined as the DefinedData class/model, but the DynamicData is basically miscellaneous information we get about the root object dependent on things. If I were to actually define all the options there would be thousands and it would be a daily maintenance of adding new possibilities while 99% of the root objects only have about 10 that apply to them.
My ultimate question here is how to deserialize JSON string data from an API call into a C# dynamic child class and then reference that data. Something like:
Console.WriteLine(rootObject.DynamicData["dynamicField"];
or
Console.WriteLine(rootObject.DynamicData.dynamicField);