问题
The .NET Json serializer serializes Double.PositiveInfinity and the like to things like Infinity, which aren't valid JSON. I'm now trying to use Json.NET to serialize an object to JSON, but I'd like to wrap it so that values like Infinity get converted to NULL, or the string "Infinity". How do I go about doing this?
回答1:
The only way to do this is to serialize Double
values as a custom type which provide information on top of the value. For example
{
'isInfinity': 'true',
'isNan': 'false'
'value': '0' };
This can be done pretty easily by using a wrapper type to handle Double
values
[DataContract]
public sealed class DoubleWrapper {
[DataMember]
public bool isInfinity;
[DataMember]
public bool isNaN;
[DataMember]
public double value;
public DoubleWrapper(double p) {
isInfinity = Double.IsInfinity(p);
isNaN = Double.IsNaN(p);
value = p;
}
}
来源:https://stackoverflow.com/questions/7997657/how-do-you-handle-infinity-in-json-generated-in-net