比较两个相同结构的任意JToken-s

本文关键字:结构 任意 JToken-s 两个 比较 | 更新日期: 2023-09-27 18:16:52

我想比较两个相同类型和结构的任意jtoken (Json。. Net from NewtonSoft)。

static int CompareTokens(JToken x, JToken y);  
// possible output: 0 / 1 / -1

主要目标是能够使用这个方法排序两个Json字符串,所以即使在开始他们有相同的数据,但在不同的顺序,在最后这是两个完全相同的字符串。所以排序标准并不重要,重要的是这个标准总是相同的。而每一个小的数据元素都应该考虑进去。

JToken可以是以下几种类型之一:Array, Boolean, Date, Float, Guid, Integer, Null, Object, Property, String, TimeSpan, Uri。我没有考虑比较Bytes, Comment, Constructor, None, Undefined, Raw

    比较JArraysJObjects将是很好的。这应该是某种递归比较,因为JArrays可能由其他JArrays jobobjects 组成,反之亦然。如有任何想法,我将不胜感激。
  • 但是知道比较简单的类型也会很有帮助。我想知道如何从JToken转换为实际类型(而不是知道如何在逻辑上做到这一点)。
  • JValue已经实现了IComparable,但是我不知道如何将简单类型的JToken转换为JValue。了解这一点也会有所帮助。

比较两个相同结构的任意JToken-s

在Linq-to-JSON中,JValue代表一个原始值(字符串、数字、布尔值等)。它实现了IComparable<JValue>,所以是Json。. NET会为你对原始值进行排序。

在此基础上,您将需要并行地递归地下降两个JToken对象层次结构。当您遇到第一个标记具有不同的。net类型,或不同的属性(如果不是JValue),或具有不同的值(如果是JValue)时,您需要返回比较值。

请牢记以下内容:

  • 比较方法应该是自反的、反对称的和传递的。
  • 不同。net类型的容器令牌需要以某种一致的方式按类型排序。
  • JArrayJConstructor的子令牌排序。
  • JObject的子令牌不是,所以它们需要以某种稳定、对称的方式进行比较。按照属性名的顺序行走似乎是可行的。
  • 没有明显的方法来比较JRaw,所以不要尝试,让异常被抛出。

下面是一个原型实现:

public class JTokenComparer : IComparer<JToken>
{
    public static JTokenComparer Instance { get { return instance; } }
    static JTokenComparer instance;
    static JTokenComparer()
    {
        instance = new JTokenComparer();
    }
    readonly Dictionary<Type, KeyValuePair<int, IComparer<JToken>>> dict;
    JTokenComparer()
    {
        dict = new Dictionary<Type, KeyValuePair<int, IComparer<JToken>>>
        {
            // Order chosen semi-arbitrarily.  Putting values first seems reasonable though.
            {typeof(JValue), new KeyValuePair<int, IComparer<JToken>>(0, new JValueComparer()) },
            {typeof(JProperty), new KeyValuePair<int, IComparer<JToken>>(1, new JPropertyComparer()) },
            {typeof(JArray), new KeyValuePair<int, IComparer<JToken>>(2, new JArrayComparer()) },
            {typeof(JObject), new KeyValuePair<int, IComparer<JToken>>(3, new JObjectComparer()) },
            {typeof(JConstructor), new KeyValuePair<int, IComparer<JToken>>(4, new JConstructorComparer()) },
        };
    }
    #region IComparer<JToken> Members
    public int Compare(JToken x, JToken y)
    {
        if (x is JRaw || y is JRaw)
            throw new InvalidOperationException("Tokens of type JRaw cannot be sorted");
        if (object.ReferenceEquals(x, y))
            return 0;
        else if (x == null)
            return -1;
        else if (y == null)
            return 1;
        var typeData1 = dict[x.GetType()];
        var typeData2 = dict[y.GetType()];
        int comp;
        if ((comp = typeData1.Key.CompareTo(typeData2.Key)) != 0)
            return comp;
        if (typeData1.Value != typeData2.Value)
            throw new InvalidOperationException("inconsistent dictionary values"); // Internal error
        return typeData2.Value.Compare(x, y);
    }
    #endregion
}
abstract class JTokenComparerBase<TJToken> : IComparer<JToken> where TJToken : JToken
{
    protected TJToken CheckType(JToken item)
    {
        if (item != null && item.GetType() != typeof(TJToken))
            throw new ArgumentException(string.Format("Actual type {0} of token '"{1}'" does not match expected type {2}", item.GetType(), item, typeof(TJToken)));
        return (TJToken)item;
    }
    protected bool TryBaseCompare(TJToken x, TJToken y, out int comparison)
    {
        CheckType(x);
        CheckType(y);
        if (object.ReferenceEquals(x, y))
        {
            comparison = 0;
            return true;
        }
        else if (x == null)
        {
            comparison = -1;
            return true;
        }
        else if (y == null)
        {
            comparison = 1;
            return true;
        }
        comparison = 0;
        return false;
    }
    protected abstract int CompareDerived(TJToken x, TJToken y);
    protected int TokenCompare(JToken x, JToken y)
    {
        var tx = CheckType(x);
        var ty = CheckType(y);
        int comp;
        if (TryBaseCompare(tx, ty, out comp))
            return comp;
        return CompareDerived(tx, ty);
    }
    #region IComparer<JToken> Members
    int IComparer<JToken>.Compare(JToken x, JToken y)
    {
        return TokenCompare(x, y);
    }
    #endregion
}
abstract class JContainerOrderedComparerBase<TJToken> : JTokenComparerBase<TJToken> where TJToken : JContainer
{
    protected int CompareItemsInOrder(TJToken x, TJToken y)
    {
        int comp;
        // Dictionary order: sort on items before number of items.
        for (int i = 0, n = Math.Min(x.Count, y.Count); i < n; i++)
            if ((comp = JTokenComparer.Instance.Compare(x[i], y[i])) != 0)
                return comp;
        if ((comp = x.Count.CompareTo(y.Count)) != 0)
            return comp;
        return 0;
    }
}
class JPropertyComparer : JTokenComparerBase<JProperty>
{
    protected override int CompareDerived(JProperty x, JProperty y)
    {
        int comp;
        if ((comp = x.Name.CompareTo(y.Name)) != 0)
            return comp;
        return JTokenComparer.Instance.Compare(x.Value, y.Value);
    }
}
class JObjectComparer : JTokenComparerBase<JObject>
{
    protected override int CompareDerived(JObject x, JObject y)
    {
        int comp;
        // Dictionary order: sort on items before number of items.
        // Order both property sequences to preserve reflexivity.
        foreach (var propertyComp in x.Properties().OrderBy(p => p.Name).Zip(y.Properties().OrderBy(p => p.Name), (xp, yp) => JTokenComparer.Instance.Compare(xp, yp)))
            if (propertyComp != 0)
                return propertyComp;
        if ((comp = x.Count.CompareTo(y.Count)) != 0)
            return comp;
        return 0;
    }
}
class JArrayComparer : JContainerOrderedComparerBase<JArray>
{
    protected override int CompareDerived(JArray x, JArray y)
    {
        int comp;
        if ((comp = CompareItemsInOrder(x, y)) != 0)
            return comp;
        return 0;
    }
}
class JConstructorComparer : JContainerOrderedComparerBase<JConstructor>
{
    protected override int CompareDerived(JConstructor x, JConstructor y)
    {
        int comp;
        if ((comp = x.Name.CompareTo(y.Name)) != 0)
            return comp;
        if ((comp = CompareItemsInOrder(x, y)) != 0)
            return comp;
        return 0;
    }
}
class JValueComparer : JTokenComparerBase<JValue>
{
    protected override int CompareDerived(JValue x, JValue y)
    {
        return Comparer<JToken>.Default.Compare(x, y); // JValue implements IComparable<JValue>
    }
}

原型提琴。

实际上,这可以用更少的代码完成。不太好,因为使用字符串比较代替JValue比较。

下面不是我问题的确切答案,但目标达到了。

    public static JToken Normalize(this JToken token)
    {
        var result = token;
        switch (token.Type)
        {
            case JTokenType.Object:
                var jObject = (JObject)token;
                if (jObject != null && jObject.HasValues)
                {
                    var newObject = new JObject();
                    foreach (var property in jObject.Properties().OrderBy(x => x.Name).ToList())
                    {
                        var value = property.Value as JToken;
                        if (value != null)
                        {
                            value = Normalize(value);
                        }
                        newObject.Add(property.Name, value);
                    }
                    return newObject;
                }
                break;
            case JTokenType.Array:
                var jArray = (JArray)token;
                if (jArray != null && jArray.Count > 0)
                {
                    var normalizedArrayItems = jArray
                        .Select(x => Normalize(x))
                        .OrderBy(x => x.ToString(), StringComparer.Ordinal);
                    result = new JArray(normalizedArrayItems);
                }
                break;
            default:
                break;
        }
        return result;
    }