Search code examples
c#asp.net-core-webapi

Multiple data types in the object part of a Dictionary<string, object>


I need to send this object through a CMS API into the controller:

{
    "configData":[{"filename":"tttttttt"},{"year":"2024"},{"month":"03"}],
    "unitData":[{"a":0,"b":1,"c":"asd"},{"a":0,"b":1,"c":"dsa"}]
}

Then the controller:

public string createAuditRels([FromBody] Dictionary<string,object> apiData)
{
    var apiConfigData = apiData["configData"] as Dictionary<string,string>;
    var filename = apiConfigData["filename"];
    ...
}

But I'm getting an error:

Object reference not set to an instance of an object.

Is this data structure possible (multiple data types in the objects type)?


Solution

  • Your configData is an array of objects but not an object. So you will get null when you are trying to cast to Dictionary<string, string>.

    Cast it as List<Dictionary<string, string>> type.

    var apiConfigData = apiData["configData"] as List<Dictionary<string, string>>;
    var filename = apiConfigData[0]["filename"];
    

    Alternative, you can create a model class for your request body.

    public class AuditRelModel
    {
        public List<ConfigDataModel> ConfigData { get; set; }
        public List<UnitDataModel> UnitData { get; set; }
    }
    
    public class ConfigDataModel
    {
        public string Filename { get; set; }
        public string Year { get; set; }
        public string Month { get; set; }
    }
    
    public class UnitDataModel
    {
        public int A { get; set; }
        public int B { get; set; }
        public string C { get; set; }
    }
    
    public string createAuditRels([FromBody] AuditRelModel apiData)
    {
        var filename = apiData.ConfigData[0].Filename;
    }