本文介绍了你如何处理无限的JSON在.NET中产生的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在.NET JSON序列化序列化Double.PositiveInfinity之类的东西一样无限,这是不是有效的JSON。我现在试图用Json.NET为一个对象序列化到JSON,但我希望把它包起来,这样像无限值会转换为NULL,或字符串无限。我该如何去这样做?

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?

推荐答案

要做到这一点,唯一的办法就是为它提供顶级的信息自定义类型序列化双击值的值。例如

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' };

这可以很容易地通过使用包装类型来处理双击值做pretty的

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;
  }
}

这篇关于你如何处理无限的JSON在.NET中产生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 07:29