How do you handle Infinity in JSON generated in .NET

只愿长相守 提交于 2019-12-10 21:07:56

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!