2016-05-14 57 views
0

我需要一个好的设计来解决这个问题。检查两个JSON的通用名称是否有相同的值

我每次调用Web API时都会得到两个单独的JSON字符串。我们将它们命名为recieve1recieve2。如果它们具有相同的值,我需要检查的所有常见名称recieve1recieve2。如果recieve2中有一些名称值对在recieve1中不存在,则表示没有问题(反之亦然)。但我不知道json字符串的名称值对。因为每次我打电话给这个API时,我都可能会得到一双新的JSON。例如,在第一次调用我能得到这个

recieve1

{ 
    "employees": [ 
    { 
     "firstName": "John", 
     "lastName": "Doe" 
    }, 
    { 
     "firstName": "Anna", 
     "lastName": "Smith" 
    }, 
    { 
     "firstName": "Peter", 
     "lastName": "Jones" 
    } 
    ] 
} 

recieve2

{ 
    "employees": [ 
    { 
     "firstName": "John", 
     "lastName": "Doe", 
     "Sex": "Male" 

    }, 
    { 
     "firstName": "Anna", 
     "lastName": "Smith" 
    }, 
    { 
     "firstName": "Peter", 
     "lastName": "Jones", 
     "age": "100" // recieve1 does not have this name value pair 
         // But that is Ok they are still equivalent 
    } 
    ] 
} 

通过我的要求这两个是“等价”。让我们来看看相当于JSONs的另一个例子,在第二次调用我们得到, recieve1

{"menu": 
    { 
    "id": "1", 
    "name": "Second Call Return", 
    "ReturnCanHaveArrays": { 
     "array": [ 
     {"isCommon": "Yes", "id": "1"}, 
     {"isCommon ": "Yes", "id": "4"}, 
     {"isCommon": "No", "id": "100"} 
     ] 
    } 
    } 
} 

recieve2

{"menu": 
    { 
    "id": "1", 
    "name": "Second Call Return", 
    "newProperty" : "This is not present in recieve1. But that is ok" 
    "ReturnCanHaveArrays": { 
     "array": [ 
     {"isCommon": "Yes", "id": "1"}, 
     {"isCommon ": "Yes", "id": "4"} 
     ] 
    } 
    } 
} 

以上两种jsons也是相等。但以下两个都不是:

recieve1

{"menu": { 
    "id": "1" 
}} 

recieve2

{"menu": { 
    "id": "10" // not equivalent. 
}} 

正如你可以看到我不能确定的属性设置了手。我怎么解决这个问题?

  • 语言:c#(重要的,必须使用c#)。
  • NET版本:不重要
  • 请建议解决此问题的最佳设计。
  • 如有必要,请使用任何技术。 在此先感谢

回答

0

如果您正在使用JSON.net,这是相当琐碎。

bool AreEquiv(JObject a, JObject b) 
{ 
    foreach (var prop in a) 
    { 
     JToken aValue = prop.Value; 
     JToken bValue; 
     if (b.TryGetValue(prop.Key, StringComparison.OrdinalIgnoreCase, out bValue)) 
     { 
      if (aValue.GetType() != bValue.GetType()) 
       return false; 

      if (aValue is JObject) 
      { 
       if (!AreEquiv((JObject)aValue, (JObject)bValue)) 
        return false; 
      } 
      else if (!prop.Value.Equals(bValue)) 
       return false; 
     } 
    } 

    return true; 
} 

该代码将遍历两个JObject,比较非对象值,并递归地调用该函数用于任何内JObject。如果在ab中均未找到密钥,则会跳过该密钥。

相关问题