Search code examples
c#jsontestingversioning

How to test if a Json "contains" another Json in C#


Let's say I have 2 Jsons:

  Json1
  {
    "a": 1,
    "b": {
      "b1": 21,
    }
  }
  Json2
  {
    "a": 1,
    "b": {
      "b1": 21,
      "b2": 22
    },
    "c": 3
  }

Here Json2 "contains" Json1 since for each field we have the same value (including nested fields, such as b.b1). The use-case here is to verify no versioning change.

How would I test for this, besides implementing the logic myself?


Solution

  • With Newtonsoft.Json you could do it like that:

    var reference = JObject.Parse("{\"a\": 1, \"b\": 2}");
    var contained = JObject.Parse("{\"b\": 2}");
    var notContained = JObject.Parse("{\"b\": 2, \"c\": 3}");
    
    var mergedContained = (JObject)reference.DeepClone();
    mergedContained.Merge(contained);
    Debug.Assert(JToken.DeepEquals(mergedContained, reference));
    
    var mergedNotContained = (JObject)reference.DeepClone();
    mergedNotContained.Merge(notContained);
    Debug.Assert(!JToken.DeepEquals(mergedNotContained, reference));
    

    But all the cloning and merging looks kinda dumb. I'd rather write a recursive algorithm that traverses a JSON structure and compares it with another on the fly.