using JetBrains.Annotations; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using WireMock.Validation; namespace WireMock.Matchers { /// /// JsonMatcher /// public class JsonMatcher : IValueMatcher { /// public object Value { get; } /// public string Name => "JsonMatcher"; /// public MatchBehaviour MatchBehaviour { get; } /// /// Initializes a new instance of the class. /// /// The string value to check for equality. public JsonMatcher([NotNull] string value) : this(MatchBehaviour.AcceptOnMatch, value) { } /// /// Initializes a new instance of the class. /// /// The object value to check for equality. public JsonMatcher([NotNull] object value) : this(MatchBehaviour.AcceptOnMatch, value) { } /// /// Initializes a new instance of the class. /// /// The match behaviour. /// The string value to check for equality. public JsonMatcher(MatchBehaviour matchBehaviour, [NotNull] string value) { Check.NotNull(value, nameof(value)); MatchBehaviour = matchBehaviour; Value = value; } /// /// Initializes a new instance of the class. /// /// The match behaviour. /// The object value to check for equality. public JsonMatcher(MatchBehaviour matchBehaviour, [NotNull] object value) { Check.NotNull(value, nameof(value)); MatchBehaviour = matchBehaviour; Value = value; } /// public double IsMatch(object input) { bool match = false; // When input is null or byte[], return Mismatch. if (input != null && !(input is byte[])) { try { // Check if JToken or object JToken jtokenInput = input is JToken tokenInput ? tokenInput : JObject.FromObject(input); // Check if JToken or string or object JToken jtokenValue; switch (Value) { case JToken tokenValue: jtokenValue = tokenValue; break; case string stringValue: jtokenValue = JToken.Parse(stringValue); break; default: jtokenValue = JObject.FromObject(Value); break; } match = JToken.DeepEquals(jtokenValue, jtokenInput); } catch (JsonException) { // just ignore JsonException } } return MatchBehaviourHelper.Convert(MatchBehaviour, MatchScores.ToScore(match)); } } }