Hello I am wondering if anyone could help me, I am trying to automatically replace NaN from double values automatically with 0 upon deserializing automatically in Web API 2. I am trying to use JSON.NET but I am having no success. Any help would be greatly appreciated. I am placing the below into my WebApiConfig
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
MediaTypeHeaderValue appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
JsonMediaTypeFormatter jsonFormatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
jsonFormatter.SerializerSettings.FloatFormatHandling = Newtonsoft.Json.FloatFormatHandling.DefaultValue;
jsonFormatter.SerializerSettings.MissingMemberHandling = MissingMemberHandling.Ignore;
jsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.None;
jsonFormatter.SerializerSettings.DateFormatHandling = DateFormatHandling.IsoDateFormat;
jsonFormatter.SerializerSettings.FloatParseHandling = FloatParseHandling.Double;
jsonFormatter.SerializerSettings.DefaultValueHandling = DefaultValueHandling.Populate;
The NaN values are not being removed and being put inside the class in a
public double Price { get; set; }
So inside of a number I get NaN inside.
I eventually figured out how to solve the issue for both read and write.
jsonFormatter.SerializerSettings.Converters.Add(new FloatConverter());
public class FloatConverter : JsonConverter
{
public override bool CanRead
{
get
{
return true;
}
}
public override bool CanWrite
{
get
{
return true;
}
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value == null)
{
writer.WriteNull();
return;
}
var val = Convert.ToDouble(value);
if (Double.IsNaN(val) || Double.IsInfinity(val))
{
writer.WriteNull();
return;
}
if (value is float)
writer.WriteValue((float)value);
else
writer.WriteValue((double)value);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
var value = JValue.Load(reader);
var val = Convert.ToDouble(value);
if (objectType == typeof(Double))
{
if (Double.IsNaN(val) || Double.IsInfinity(val))
return (Double)0.00;
else
return (Double)value;
}
if (objectType == typeof(float?))
return (float?)value;
else
return (float)value;
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(double) || objectType == typeof(float);
}
}
来源:https://stackoverflow.com/questions/42682371/removing-nan-values-in-deserialization-web-api-2-c-sharp