【问题标题】:Compare two JSON objects with tolerance for numbers比较两个具有数字容差的 JSON 对象
【发布时间】:2014-06-18 23:30:23
【问题描述】:

我目前正在使用 Java 的 Jackson JSON 库来比较一些 JSON 对象。

JSON 对象包含一些数学计算的结果。例如:

{
  name:"result_set_1"
  result:[0.123151351353,1.0123151533,2.0123051353]
}

将这些与参考实现进行比较时,我注意到某些浏览器产生的结果略有不同。这很好,但我需要以某种方式确保我在比较数字时有一个容差。

JSONNode.equals() 实际上做了一个很好的 deep-equals,但它比较 Numbers 的方式迫使它们完全相等。我需要添加一个容差。

有没有办法用容差进行深度相等?

我现在发现的唯一方法是遍历每个节点,检查它是否是一个数字,然后进行容差检查而不是等号。但是这种方法非常庞大,因为您必须检查节点是否是对象、数组、字符串……等等……并为每个节点做特定的事情。我只想要 Numbers 的自定义行为。

有没有更优雅的方式来做到这一点?任何第三方库?

【问题讨论】:

    标签: java jackson equals


    【解决方案1】:

    前言:用DeserializationFeature.USE_BIGDECIMAL_FOR_FLOATS配置你的ObjectMapper;默认情况下,Jackson 会将“非整数”JSON 数字反序列化为 doubles,但如果这样做,您将失去精度。

    这是一个改编自我写的one Equivalence<JsonNode> 的例子;您必须覆盖 doNumEquivalent() 和 doNumHash() 以满足您的需求。这意味着您使用 Guava,但实际上您应该使用。

    注意,是的,有一个哈希;您可能需要也可能不需要它,但这样做并没有什么坏处,尤其是因为这意味着您将能够使用Set<Equivalence.Wrapper<JsonNode>>(您必须使用.add(myEquivalence.wrap(myNode))。

    注2:NodeType是我的一个特定类;对于“核心杰克逊”,您想改用JsonNode 的.getNodeType()。

    用法:if (myEquivalence.equivalent(a, b)) // etc etc

    public abstract class JsonNumEquivalence
        extends Equivalence<JsonNode>
    {
        // Implement!
        protected abstract boolean doNumEquivalent(final JsonNode a, final JsonNode b);
    
        // Implement!
        protected abstract int doNumHash(final JsonNode t);
    
        @Override
        protected final boolean doEquivalent(final JsonNode a, final JsonNode b)
        {
            /*
             * If both are numbers, delegate to the helper method
             */
            if (a.isNumber() && b.isNumber())
                return doNumEquivalent(a, b);
    
            final NodeType typeA = NodeType.getNodeType(a);
            final NodeType typeB = NodeType.getNodeType(b);
    
            /*
             * If they are of different types, no dice
             */
            if (typeA != typeB)
                return false;
    
            /*
             * For all other primitive types than numbers, trust JsonNode
             */
            if (!a.isContainerNode())
                return a.equals(b);
    
            /*
             * OK, so they are containers (either both arrays or objects due to the
             * test on types above). They are obviously not equal if they do not
             * have the same number of elements/members.
             */
            if (a.size() != b.size())
                return false;
    
            /*
             * Delegate to the appropriate method according to their type.
             */
            return typeA == NodeType.ARRAY ? arrayEquals(a, b) : objectEquals(a, b);
        }
    
        @Override
        protected final int doHash(final JsonNode t)
        {
            /*
             * If this is a numeric node, delegate to the helper method
             */
            if (t.isNumber())
                return doNumHash(t);
    
            /*
             * If this is a primitive type (other than numbers, handled above),
             * delegate to JsonNode.
             */
            if (!t.isContainerNode())
                return t.hashCode();
    
            /*
             * The following hash calculations work, yes, but they are poor at best.
             * And probably slow, too.
             *
             * TODO: try and figure out those hash classes from Guava
             */
            int ret = 0;
    
            /*
             * If the container is empty, just return
             */
            if (t.size() == 0)
                return ret;
    
            /*
             * Array
             */
            if (t.isArray()) {
                for (final JsonNode element: t)
                    ret = 31 * ret + doHash(element);
                return ret;
            }
    
            /*
             * Not an array? An object.
             */
            final Iterator<Map.Entry<String, JsonNode>> iterator = t.fields();
    
            Map.Entry<String, JsonNode> entry;
    
            while (iterator.hasNext()) {
                entry = iterator.next();
                ret = 31 * ret
                    + (entry.getKey().hashCode() ^ doHash(entry.getValue()));
            }
    
            return ret;
        }
    
        private boolean arrayEquals(final JsonNode a, final JsonNode b)
        {
            /*
             * We are guaranteed here that arrays are the same size.
             */
            final int size = a.size();
    
            for (int i = 0; i < size; i++)
                if (!doEquivalent(a.get(i), b.get(i)))
                    return false;
    
            return true;
        }
    
        private boolean objectEquals(final JsonNode a, final JsonNode b)
        {
            /*
             * Grab the key set from the first node
             */
            final Set<String> keys = Sets.newHashSet(a.fieldNames());
    
            /*
             * Grab the key set from the second node, and see if both sets are the
             * same. If not, objects are not equal, no need to check for children.
             */
            final Set<String> set = Sets.newHashSet(b.fieldNames());
            if (!set.equals(keys))
                return false;
    
            /*
             * Test each member individually.
             */
            for (final String key: keys)
                if (!doEquivalent(a.get(key), b.get(key)))
                    return false;
    
            return true;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-29
      • 1970-01-01
      • 2023-03-26
      相关资源
      最近更新 更多