首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在JToken.DeepEquals中,System.Text.Json中什么是等价的?

在JToken.DeepEquals中,System.Text.Json中什么是等价的?
EN

Stack Overflow用户
提问于 2020-03-07 18:11:25
回答 2查看 5.6K关注 0票数 11

我想将我的代码从Newtonsoft Json.Net迁移到微软标准System.Text.Json。但是我找不到替代JToken.DeepEqual的方法

基本上,代码必须在单元测试中比较两个JSON。引用JSON,并得到结果JSON。我使用Newtonsoft中的机制创建了两个JObject,然后将它们与JToken.DeepEqual进行比较。下面是示例代码:

代码语言:javascript
复制
[TestMethod]
public void ExampleUnitTes()
{
    string resultJson = TestedUnit.TestedMethod();
    string referenceJson =
    @"
    {
      ...bla bla bla...
      ...some JSON Content...
      ...bla bla bla...
    }";

    JObject expected = ( JObject )JsonConvert.DeserializeObject( referenceJson );
    JObject result = ( JObject )JsonConvert.DeserializeObject( resultJson );
    Assert.IsTrue( JToken.DeepEquals( result, expected ) );
}

如果我是正确的Newtonsoft JObject类似于System.Text.Json.JsonDocument,并且我能够创建它,只是我不知道如何比较它的内容。

代码语言:javascript
复制
System.Text.Json.JsonDocument expectedDoc = System.Text.Json.JsonDocument.Parse( referenceJson );
System.Text.Json.JsonDocument resultDoc = System.Text.Json.JsonDocument.Parse( json );

Compare???( expectedDoc, resulDoc );

当然,字符串比较不是一个解决方案,因为JSON的格式并不重要,属性的顺序也不重要。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-03-08 21:38:31

System.Text.Json中,.Net 3.1中没有类似的内容,因此我们将不得不推出自己的版本。这里有一个可能的IEqualityComparer<JsonElement>

代码语言:javascript
复制
public class JsonElementComparer : IEqualityComparer<JsonElement>
{
    public JsonElementComparer() : this(-1) { }

    public JsonElementComparer(int maxHashDepth) => this.MaxHashDepth = maxHashDepth;

    int MaxHashDepth { get; } = -1;

    #region IEqualityComparer<JsonElement> Members

    public bool Equals(JsonElement x, JsonElement y)
    {
        if (x.ValueKind != y.ValueKind)
            return false;
        switch (x.ValueKind)
        {
            case JsonValueKind.Null:
            case JsonValueKind.True:
            case JsonValueKind.False:
            case JsonValueKind.Undefined:
                return true;
                
            // Compare the raw values of numbers, and the text of strings.
            // Note this means that 0.0 will differ from 0.00 -- which may be correct as deserializing either to `decimal` will result in subtly different results.
            // Newtonsoft's JValue.Compare(JTokenType valueType, object? objA, object? objB) has logic for detecting "equivalent" values, 
            // you may want to examine it to see if anything there is required here.
            // https://github.com/JamesNK/Newtonsoft.Json/blob/master/Src/Newtonsoft.Json/Linq/JValue.cs#L246
            case JsonValueKind.Number:
                return x.GetRawText() == y.GetRawText();

            case JsonValueKind.String:
                return x.GetString() == y.GetString(); // Do not use GetRawText() here, it does not automatically resolve JSON escape sequences to their corresponding characters.
                
            case JsonValueKind.Array:
                return x.EnumerateArray().SequenceEqual(y.EnumerateArray(), this);
            
            case JsonValueKind.Object:
                {
                    // Surprisingly, JsonDocument fully supports duplicate property names.
                    // I.e. it's perfectly happy to parse {"Value":"a", "Value" : "b"} and will store both
                    // key/value pairs inside the document!
                    // A close reading of https://www.rfc-editor.org/rfc/rfc8259#section-4 seems to indicate that
                    // such objects are allowed but not recommended, and when they arise, interpretation of 
                    // identically-named properties is order-dependent.  
                    // So stably sorting by name then comparing values seems the way to go.
                    var xPropertiesUnsorted = x.EnumerateObject().ToList();
                    var yPropertiesUnsorted = y.EnumerateObject().ToList();
                    if (xPropertiesUnsorted.Count != yPropertiesUnsorted.Count)
                        return false;
                    var xProperties = xPropertiesUnsorted.OrderBy(p => p.Name, StringComparer.Ordinal);
                    var yProperties = yPropertiesUnsorted.OrderBy(p => p.Name, StringComparer.Ordinal);
                    foreach (var (px, py) in xProperties.Zip(yProperties))
                    {
                        if (px.Name != py.Name)
                            return false;
                        if (!Equals(px.Value, py.Value))
                            return false;
                    }
                    return true;
                }
                
            default:
                throw new JsonException(string.Format("Unknown JsonValueKind {0}", x.ValueKind));
        }
    }

    public int GetHashCode(JsonElement obj)
    {
        var hash = new HashCode(); // New in .Net core: https://learn.microsoft.com/en-us/dotnet/api/system.hashcode
        ComputeHashCode(obj, ref hash, 0);
        return hash.ToHashCode();
    }

    void ComputeHashCode(JsonElement obj, ref HashCode hash, int depth)
    {
        hash.Add(obj.ValueKind);

        switch (obj.ValueKind)
        {
            case JsonValueKind.Null:
            case JsonValueKind.True:
            case JsonValueKind.False:
            case JsonValueKind.Undefined:
                break;
                
            case JsonValueKind.Number:
                hash.Add(obj.GetRawText());
                break;

            case JsonValueKind.String:
                hash.Add(obj.GetString());
                break;
                
            case JsonValueKind.Array:
                if (depth != MaxHashDepth)
                    foreach (var item in obj.EnumerateArray())
                        ComputeHashCode(item, ref hash, depth+1);
                else
                    hash.Add(obj.GetArrayLength());
                break;
            
            case JsonValueKind.Object:
                foreach (var property in obj.EnumerateObject().OrderBy(p => p.Name, StringComparer.Ordinal))
                {
                    hash.Add(property.Name);
                    if (depth != MaxHashDepth)
                        ComputeHashCode(property.Value, ref hash, depth+1);
                }
                break;
                
            default:
                throw new JsonException(string.Format("Unknown JsonValueKind {0}", obj.ValueKind));
        }            
    }
    
    #endregion
}

请按以下方式使用:

代码语言:javascript
复制
var comparer = new JsonElementComparer();
using var doc1 = System.Text.Json.JsonDocument.Parse(referenceJson);
using var doc2 = System.Text.Json.JsonDocument.Parse(resultJson);
Assert.IsTrue(comparer.Equals(doc1.RootElement, doc2.RootElement));

备注:

  • 由于Json.NET在解析期间将浮点JSON值解析为doubledecimal,因此JToken.DeepEquals()认为只有尾随零点不同的浮点值是相同的。即通过以下断言: Assert.IsTrue(JToken.DeepEquals(JToken.Parse("1.0"),JToken.Parse(“1.00”)); 我的比较者,而不是,认为这两者是相等的。我认为这是可取的,因为应用程序有时希望保留尾随零,例如,当反序列化到decimal时,因此这种差异有时可能很重要。(例如,参见*不序列化小数的Json.Net两次使用相同的方式)如果您想要认为这些JSON值是相同的,则需要修改JsonValueKind.NumberComputeHashCode()Equals(JsonElement x, JsonElement y)中的大小写,以便在小数点后出现尾随零。
  • 令人惊讶的是,令人惊讶的是,JsonDocument完全支持重复的属性名,这使上述问题变得更加困难!也就是说,它非常乐意解析{"Value":"a", "Value" : "b"}并将两个键/值对存储在文档中。 仔细阅读https://www.rfc-editor.org/rfc/rfc8259#section-4似乎表明这类对象是允许的,但不推荐使用,当它们出现时,对同名属性的解释可能是顺序依赖的。我通过稳定地按属性名对属性列表进行排序,然后遍历列表并比较名称和值来处理这一问题。如果您不关心重复的属性名称,那么可能通过使用单个查找字典而不是使用两个排序列表来提高性能。
  • JsonDocument是一次性的,实际上需要根据文档处理: 这个类利用池内存中的资源来最小化垃圾收集器(GC)在高使用率场景中的影响。如果不能正确地释放该对象,将导致内存没有返回到池中,这将增加对框架各个部分的GC影响。

在你的问题中,你没有这样做,但你应该这样做。

演示小提琴这里

票数 14
EN

Stack Overflow用户

发布于 2022-04-20 07:40:50

更新

由于我的1.3.0版的SystemTextJson.JsonDiffPatch NuGet包,您可以使用可拓法来比较JsonDocumentJsonElementJsonNode

原来的答案在下面

对于自System.Text.Json.Nodes命名空间 6发布以来引入的.NET,目前有一个Github问题来讨论向JsonNode添加DeepEquals功能。

我将自己的DeepEquals实现作为SystemTextJson.JsonDiffPatch NuGet包的一部分。默认情况下,扩展会比较JSON值的原始文本,这不是JToken.DeepEquals所做的。需要启用语义相等,因为:

代码语言:javascript
复制
var node1 = JsonNode.Parse("[1.0]");
var node2 = JsonNode.Parse("[1]");

// false
bool equal = node1.DeepEquals(node2);
// true
bool semanticEqual = node1.DeepEquals(node2, JsonElementComparison.Semantic);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60580743

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档