I have a json string I am trying to serialize into an object, but some of the values are 'null', not null as in empty, but actually the word null, unfortunately those are not string values. I attempted to add the defaultignorecondition whenwritingnull, but that alone doesn't seem to work. The error is:
InvalidOperationException: Cannot get the value of a token type 'Null' as a number
My code:
var settings = new JsonSerializerOptions
{
DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull
};
gdata = JsonSerializer.Deserialize<List<gasData>>(response.Content, settings);
Example from the json raw data:
"no_offset":0.0000,"no_units":"ppb","so2_sensor_serial_number":null,"so2_state":"Not Fitted","so2_prescaled":null
CodePudding user response:
Try this code, it is working properly
var json = "{\"no_offset\":0,\"no_units\":\"ppb\",\"so2_sensor_serial_number\":null,\"so2_state\":\"Not Fitted\",\"so2_prescaled\":null}";
var data = System.Text.Json.JsonSerializer.Deserialize<Data>(json);
class
public partial class Data
{
[JsonPropertyName("no_offset")]
public long? NoOffset { get; set; }
[JsonPropertyName("no_units")]
public string NoUnits { get; set; }
[JsonPropertyName("so2_sensor_serial_number")]
public long? So2SensorSerialNumber { get; set; }
[JsonPropertyName("so2_state")]
public string So2State { get; set; }
[JsonPropertyName("so2_prescaled")]
public object So2Prescaled { get; set; }
}