如何在flutter/dart中比较Json数据方法

w3nuxt5m  于 2023-06-19  发布在  Flutter
关注(0)|答案(2)|浏览(170)

我有数据,我想创建方法来比较这个数据与JSON数据从API有人知道如何做到这一点?

e4eetjau

e4eetjau1#

谷歌的人似乎已经尝试过了,也许可以试试:https://github.com/google/dart-json_diff

p4rjhz4m

p4rjhz4m2#

希望我的回答对你有帮助。如果你喜欢的话就投赞成票
下面是您可以用来比较dart中的两个json的方法

bool compareJson(dynamic json1, dynamic json2) {
  // Check if the types of the objects are the same
  if (json1.runtimeType != json2.runtimeType) {
    return false;
  }

  // Compare dictionaries
  if (json1 is Map<String, dynamic> && json2 is Map<String, dynamic>) {
    // Check if both dictionaries have the same keys
    if (!json1.keys.toSet().containsAll(json2.keys.toSet()) ||
        !json2.keys.toSet().containsAll(json1.keys.toSet())) {
      return false;
    }

    // Recursively compare the values for each key
    for (var key in json1.keys) {
      if (!compareJson(json1[key], json2[key])) {
        return false;
      }
    }
    return true;
  }

  // Compare lists
  if (json1 is List<dynamic> && json2 is List<dynamic>) {
    // Check if both lists have the same length
    if (json1.length != json2.length) {
      return false;
    }

    // Recursively compare the values at each index
    for (var i = 0; i < json1.length; i++) {
      if (!compareJson(json1[i], json2[i])) {
        return false;
      }
    }
    return true;
  }

  // Compare other types of values
  return json1 == json2;
}

范例

void main() {
      // Example JSON objects
      var json1 = {
        "name": "John",
        "address": {
          "street": "123 Main St",
          "city": "New York"
        },
        "age": 30,
      };
    
      var json2 = {
        "name": "John",
        "age": 30,
        "address": {
          "street": "123 Main St",
          "city": "New York"
        }
      };
    // Compare the JSON objects
      var result = compareJson(json1, json2);
      // Check the result
      if (result) {
        print("The JSON objects are identical.");
      } else {
        print("The JSON objects are not identical.");
      }
}

相关问题