测试已解析的json映射是否相等的好方法是什么? [英] what is a good way to test parsed json maps for equality?

查看:76
本文介绍了测试已解析的json映射是否相等的好方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码打印:

false
false
true
{{a: b}, {a: b}}






代码

import "dart:json" as JSON;

main() {
  print(JSON.parse('{ "a" : "b" }') == JSON.parse('{ "a" : "b" }'));
  print({ "a" : "b" } == { "a" : "b" });
  print({ "a" : "b" }.toString() == { "a" : "b" }.toString());
  Set s = new Set();
  s.add(JSON.parse('{ "a" : "b" }'));
  s.add(JSON.parse('{ "a" : "b" }'));
  print(s);
}

我正在使用json并解析两个等效的对象,将它们存储在Set中,希望它们不会重复。事实并非如此,这似乎是因为前两行(出乎意料?)导致错误。假设每个对象都是JSON.parse()的结果,正确地比较两个Map对象的有效方法是什么?

I am using json and parsing two equivalent objects, storing them in a Set, hoping they will not be duplicated. This is not the case and it seems to be because the first two lines (unexpectedly?) results in false. What is an efficient way to correctly compare two Map objects assuming each were the result of JSON.parse()?

推荐答案

实际上非常困难,因为地图和列表上的==运算符并不真正将键/值/元素彼此进行比较。

This is actually pretty hard, as the == operator on Maps and Lists doesn't really compare keys/values/elements to each other.

根据您的用例,您可能必须编写一个实用程序方法。我曾经写过这个快速而又肮脏的函数:

Depending on your use case, you may have to write a utility method. I once wrote this quick and dirty function:

bool mapsEqual(Map m1, Map m2) {
    Iterable k1 = m1.keys;
    Iterable k2 = m2.keys;
    // Compare m1 to m2
    if(k1.length!=k2.length) return false;
    for(dynamic o in k1) {
        if(!k2.contains(o)) return false;
        if(m1[o] is Map) {
            if(!(m2[o] is Map)) return false;
            if(!mapsEqual(m1[o], m2[o])) return false;
        } else {
            if(m1[o] != m2[o]) return false;
        }
    }
    return true;
}

请注意,尽管它处理嵌套的JSON对象,但始终会返回<$一旦涉及到嵌套列表,则为c $ c> false 。如果要使用此方法,则可能需要添加代码来处理此问题。

Please note that while it handles nested JSON objects, it will always return false as soon as nested lists are involved. If you want to use this approach, you may need to add code for handling this.

我曾经开始的另一种方法是为Map和List编写包装器(实现Map /列出要正常使用的列表)并覆盖 operator == ,然后使用 JsonParser 和JsonListener可以使用这些包装器解析JSON字符串。当我很快放弃该代码时,我没有代码,也不知道它是否真的可以工作,但值得一试。

Another approach I once started was to write wrappers for Map and List (implementing Map/List to use it normally) and override operator==, then use JsonParser and JsonListener to parse JSON strings using those wrappers. As I abandoned that pretty soon, I don't have code for it and don't know if it really would have worked, but it could be worth a try.

这篇关于测试已解析的json映射是否相等的好方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆