你好,我想知道是否有人可以帮助我,我试图自动从双重值中自动替换Nan,以0在Web API中自动散发时,我正在尝试使用JSON.NET。但是我没有成功。任何帮助将不胜感激。我将下面放在我的网络上
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;
未删除NAN值,并将其放入
中的班级中public double Price { get; set; }
所以在一个数字的内部,我将nan放在里面。
我最终想出了如何解决读写的问题。
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);
}
}