'How to deserialize string to C# model with nested models
I'm passing a [FromForm] string param to a .net 6 web api controller. Looks like this.
public async Task<Dictionary<int, ReturnDataModel>> GetData([FromForm] string sensorData)
I am deserializing the string to a model .. Looks like this.
Data = JsonConvert.DeserializeObject<UserSubmittedSensorDataModel>(sensorData);
It deserializes all stand alone POCO's without fail , but it won't process the ExposureInputs model... Just remains null. I know that if I was to put that those in this model, it would deserialize fine, but I was wondering why it won't deserialize in this manner? The fields all align and are correct when I submit them. The mapping just doesn't seem to work for any model embedded in the base model. Is there a way to do this?
here's the model class
public record UserSubmittedSensorDataModel
{
public string? SensorType { get; init; }
public string? ExposureType { get; init; }
public ExposureInputsModel ExposureInputs { get; init; } // This won't deserialize
}
public record ExposureInputsModel
{
public string? ExposureType { get; init; }
public string? StandardTestMethod { get; init; }
public string? OrganizationStandardNumber { get; init; }
public string? ExposureLocation { get; init; }
}
Solution 1:[1]
I just tested this scenario because of some curiosity to see is there any binding issues while using immutable records as input for API. It is working properly. All fields are properly binding. Probably the issue is with below method signature.
public async Task<Dictionary<int, ReturnDataModel>> GetData([FromForm]
string sensorData)
Please change the type of sensorData to UserSubmittedSensorDataModel ,
you can avoid manual deserialization.
In my case it is working.
Solution 2:[2]
When I posted the question, I thought all I needed was what I posted. A reply above helped me realize my own mistake.
I am passing the sensorData parameter via a vue.js POST request.
I initially was creating an array for the ExposureInputs model, but I changed it to an object and it now deserialezes correctly.
this.exposureInputs = {
exposureType: this.exposureType,
standardTestMethod: input.isStandard.toString(),
organizationStandardNumber: input.standardNumber,
};
Grateful for the help
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | swapmeet_Lou |


