- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
是否可以将这样的两个 json 对象与 System.Text.Json?
合并?
对象 1
{
id: 1
william: "shakespeare"
}
{
william: "dafoe"
foo: "bar"
}
{
id: 1
william: "dafoe"
foo: "bar"
}
var obj1 = JObject.Parse(obj1String);
var obj2 = JObject.Parse(obj2String);
obj1.Merge(obj2);
result = settings.ToString();
System.Text.Json
?
最佳答案
已存在为 System.Text.Json
请求此功能的问题:https://github.com/dotnet/corefx/issues/42466
同时,您可以编写自己的 Merge
基于Utf8JsonWriter
的方法作为一种解决方法(因为现有的 JsonDocument
、 JsonElement
API 是只读的)。
如果您的 JSON 对象 只包含非空的简单/原始值 并且属性显示的顺序并不是特别重要,以下相对简单的代码示例应该适合您:
public static string SimpleObjectMerge(string originalJson, string newContent)
{
var outputBuffer = new ArrayBufferWriter<byte>();
using (JsonDocument jDoc1 = JsonDocument.Parse(originalJson))
using (JsonDocument jDoc2 = JsonDocument.Parse(newContent))
using (var jsonWriter = new Utf8JsonWriter(outputBuffer, new JsonWriterOptions { Indented = true }))
{
JsonElement root1 = jDoc1.RootElement;
JsonElement root2 = jDoc2.RootElement;
// Assuming both JSON strings are single JSON objects (i.e. {...})
Debug.Assert(root1.ValueKind == JsonValueKind.Object);
Debug.Assert(root2.ValueKind == JsonValueKind.Object);
jsonWriter.WriteStartObject();
// Write all the properties of the first document that don't conflict with the second
foreach (JsonProperty property in root1.EnumerateObject())
{
if (!root2.TryGetProperty(property.Name, out _))
{
property.WriteTo(jsonWriter);
}
}
// Write all the properties of the second document (including those that are duplicates which were skipped earlier)
// The property values of the second document completely override the values of the first
foreach (JsonProperty property in root2.EnumerateObject())
{
property.WriteTo(jsonWriter);
}
jsonWriter.WriteEndObject();
}
return Encoding.UTF8.GetString(outputBuffer.WrittenSpan);
}
Newtonsoft.Json
有不同
null
在进行合并时处理
null
不会覆盖非空属性的值(当有重复时)。我不确定你是否想要这种行为。如果需要,您需要修改上述方法来处理
null
案件。以下是修改:
public static string SimpleObjectMergeWithNullHandling(string originalJson, string newContent)
{
var outputBuffer = new ArrayBufferWriter<byte>();
using (JsonDocument jDoc1 = JsonDocument.Parse(originalJson))
using (JsonDocument jDoc2 = JsonDocument.Parse(newContent))
using (var jsonWriter = new Utf8JsonWriter(outputBuffer, new JsonWriterOptions { Indented = true }))
{
JsonElement root1 = jDoc1.RootElement;
JsonElement root2 = jDoc2.RootElement;
// Assuming both JSON strings are single JSON objects (i.e. {...})
Debug.Assert(root1.ValueKind == JsonValueKind.Object);
Debug.Assert(root2.ValueKind == JsonValueKind.Object);
jsonWriter.WriteStartObject();
// Write all the properties of the first document that don't conflict with the second
// Or if the second is overriding it with null, favor the property in the first.
foreach (JsonProperty property in root1.EnumerateObject())
{
if (!root2.TryGetProperty(property.Name, out JsonElement newValue) || newValue.ValueKind == JsonValueKind.Null)
{
property.WriteTo(jsonWriter);
}
}
// Write all the properties of the second document (including those that are duplicates which were skipped earlier)
// The property values of the second document completely override the values of the first, unless they are null in the second.
foreach (JsonProperty property in root2.EnumerateObject())
{
// Don't write null values, unless they are unique to the second document
if (property.Value.ValueKind != JsonValueKind.Null || !root1.TryGetProperty(property.Name, out _))
{
property.WriteTo(jsonWriter);
}
}
jsonWriter.WriteEndObject();
}
return Encoding.UTF8.GetString(outputBuffer.WrittenSpan);
}
public static string Merge(string originalJson, string newContent)
{
var outputBuffer = new ArrayBufferWriter<byte>();
using (JsonDocument jDoc1 = JsonDocument.Parse(originalJson))
using (JsonDocument jDoc2 = JsonDocument.Parse(newContent))
using (var jsonWriter = new Utf8JsonWriter(outputBuffer, new JsonWriterOptions { Indented = true }))
{
JsonElement root1 = jDoc1.RootElement;
JsonElement root2 = jDoc2.RootElement;
if (root1.ValueKind != JsonValueKind.Array && root1.ValueKind != JsonValueKind.Object)
{
throw new InvalidOperationException($"The original JSON document to merge new content into must be a container type. Instead it is {root1.ValueKind}.");
}
if (root1.ValueKind != root2.ValueKind)
{
return originalJson;
}
if (root1.ValueKind == JsonValueKind.Array)
{
MergeArrays(jsonWriter, root1, root2);
}
else
{
MergeObjects(jsonWriter, root1, root2);
}
}
return Encoding.UTF8.GetString(outputBuffer.WrittenSpan);
}
private static void MergeObjects(Utf8JsonWriter jsonWriter, JsonElement root1, JsonElement root2)
{
Debug.Assert(root1.ValueKind == JsonValueKind.Object);
Debug.Assert(root2.ValueKind == JsonValueKind.Object);
jsonWriter.WriteStartObject();
// Write all the properties of the first document.
// If a property exists in both documents, either:
// * Merge them, if the value kinds match (e.g. both are objects or arrays),
// * Completely override the value of the first with the one from the second, if the value kind mismatches (e.g. one is object, while the other is an array or string),
// * Or favor the value of the first (regardless of what it may be), if the second one is null (i.e. don't override the first).
foreach (JsonProperty property in root1.EnumerateObject())
{
string propertyName = property.Name;
JsonValueKind newValueKind;
if (root2.TryGetProperty(propertyName, out JsonElement newValue) && (newValueKind = newValue.ValueKind) != JsonValueKind.Null)
{
jsonWriter.WritePropertyName(propertyName);
JsonElement originalValue = property.Value;
JsonValueKind originalValueKind = originalValue.ValueKind;
if (newValueKind == JsonValueKind.Object && originalValueKind == JsonValueKind.Object)
{
MergeObjects(jsonWriter, originalValue, newValue); // Recursive call
}
else if (newValueKind == JsonValueKind.Array && originalValueKind == JsonValueKind.Array)
{
MergeArrays(jsonWriter, originalValue, newValue);
}
else
{
newValue.WriteTo(jsonWriter);
}
}
else
{
property.WriteTo(jsonWriter);
}
}
// Write all the properties of the second document that are unique to it.
foreach (JsonProperty property in root2.EnumerateObject())
{
if (!root1.TryGetProperty(property.Name, out _))
{
property.WriteTo(jsonWriter);
}
}
jsonWriter.WriteEndObject();
}
private static void MergeArrays(Utf8JsonWriter jsonWriter, JsonElement root1, JsonElement root2)
{
Debug.Assert(root1.ValueKind == JsonValueKind.Array);
Debug.Assert(root2.ValueKind == JsonValueKind.Array);
jsonWriter.WriteStartArray();
// Write all the elements from both JSON arrays
foreach (JsonElement element in root1.EnumerateArray())
{
element.WriteTo(jsonWriter);
}
foreach (JsonElement element in root2.EnumerateArray())
{
element.WriteTo(jsonWriter);
}
jsonWriter.WriteEndArray();
}
Merge
方法在运行时和分配方面。也就是说,可以根据需要更快地实现实现(例如,不要写缩进,缓存
outputBuffer
,不要接受/返回字符串等)。
BenchmarkDotNet=v0.12.0, OS=Windows 10.0.19041
Intel Core i7-6700 CPU 3.40GHz (Skylake), 1 CPU, 8 logical and 4 physical cores
.NET Core SDK=5.0.100-alpha1-015914
[Host] : .NET Core 5.0.0 (CoreCLR 5.0.19.56303, CoreFX 5.0.19.56306), X64 RyuJIT
Job-LACFYV : .NET Core 5.0.0 (CoreCLR 5.0.19.56303, CoreFX 5.0.19.56306), X64 RyuJIT
PowerPlanMode=00000000-0000-0000-0000-000000000000
| Method | Mean | Error | StdDev | Median | Min | Max | Ratio | Gen 0 | Gen 1 | Gen 2 | Allocated |
|---------------- |---------:|---------:|---------:|---------:|---------:|---------:|------:|-------:|-------:|------:|----------:|
| MergeNewtonsoft | 29.01 us | 0.570 us | 0.656 us | 28.84 us | 28.13 us | 30.19 us | 1.00 | 7.0801 | 0.0610 | - | 28.98 KB |
| Merge_New | 16.41 us | 0.293 us | 0.274 us | 16.41 us | 16.02 us | 17.00 us | 0.57 | 1.7090 | - | - | 6.99 KB |
关于c# - System.Text.Json 合并两个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58694837/
我有一个带有帮助页面的 Web API 2 项目,该项目在本地运行良好,但当我将其推送到 Azure 时抛出此错误: Method not found: 'System.String System.S
我有两台服务器,但通常运行相同的设置 - IIS、SQL Server 等。一台给我这个错误,另一台没有。我从 Visual Studio 向两者发布相同的代码。 它们都在运行 .NET CLR Ve
System.out声明为 public static final PrintStream out。 但是你可以调用System.setOut()重新分配它。 嗯?如果它是 final,这怎么可能?
System.out被声明为 public static final PrintStream out。 但是您可以调用System.setOut()重新分配它。 嗯?如果是 final,这怎么可能?
我有这个 linq 查询: private void GetReceivedInvoiceTasks(User user, List tasks) { var areaIds = user.A
我有一个 MonoTouch 应用程序,当我为设备编译它时,出现以下错误: Error MT2002: Can not resolve reference: System.Boolean System
您好,我有一个名为 DailyVisitReport 的 View 。在该 View 中,我有两个名为 FromDate 和 toDate 的字段。如果我选择 FromDate 和 ToDate 取决
是否可以从 ObjectContext 对象中读取元组列表? 我在存储过程中有类似这样的数据库查询 SELECT T.Id as Item1, -- this is guid T.Wo
我正在尝试创建 Odata 端点,但每当我尝试执行任何涉及日期的查询时都会收到此错误。 我在下面的非常简单示例中重新创建了它。 数据库表 EDMX(片段)
我正在尝试创建 Odata 端点,但每当我尝试执行任何涉及日期的查询时都会收到此错误。 我在下面的非常简单示例中重新创建了它。 数据库表 EDMX(片段)
我有一个方法可以从数据读取器的数据中生成类类型列表。 if (datareader != null && datareader .HasRows) { Dictionary pDict= GetP
我有一些旧的 C++ 代码,它们使用 stdio 进行输入和输出。该代码还通过 fork 生成新进程。它将 stdio 重新映射到每个新进程,以便每个 session 获取其各自的数据。 我正在考虑使
我的应用程序可以很好地构建/链接/部署到模拟器,但我只是第一次尝试将应用程序构建/部署到真实设备,并且链接器失败。 我不使用 System.Console或 ConsoleColor在我的应用程序的任
主要是我很好奇。 我们有一个名为 Unit 的对象在我们的代码库中 - 代表桥梁或道路的组件。在我们的例子中,看到带有 Unit 的 ReactiveUI 命令可能会模棱两可。作为声明中的泛型之一。
我试图将Object变量转换为StreamWriter。但是,它不起作用。有什么错? StreamWriter file = (StreamWriter) myObject; 最佳答案 myObjec
为什么以下不编译? using System; using System.Linq; using System.Linq.Expressions; public static class Extens
我正在使用 Visual Studio Community 2015 开发面向 .NET 4.5 的 Visual Basic 应用程序.我没有编写应用程序,所以我使用 NuGet 添加了所有缺失的依
我刚刚开始使用 powershell,我正在制作一个非常简单的加密功能。我想获取字符串中的每个字符,将其转换为 int 并添加一个选定的数字,然后将其转换回一个字符。 这工作正常: function
一些使用我的应用程序的人似乎变得越来越 System.MissingMethodException: Method not found: 'System.Object System.Windows.T
我是 C# 和实体的新手 我想知道是否有人在这里帮助我。我选择了哪个返回我的 customerid,所以我想将它作为参数传递给我的构造函数,我的构造函数参数类型是 guid 但我的选择类型不同,我不知
我是一名优秀的程序员,十分优秀!