我希望将我的JSON合并为一个,同时主导一个覆盖值.

例如:

下属JSON:

{
    "test": {
        "test1": true,
        "test2": {
            "test3": [1, 2, 3]
        }
    }
}

主导JSON:

{
    "test": {
        "test2": null,
        "test3": "string"
    },
    "test2": "newValue"
}

合并结果:

{
    "test": {
        "test1": true,
        "test2": null,
        "test3": "string"
    },
    "test2": "newValue"
}

用什么命令我可以做到easily

推荐答案

我用的是Newtonsoft.Json磅.

您可以使用JObject.Merge方法将两个JSON对象合并为一个,并指定如何处理这两个对象中不存在的值.

以下是一个示例代码,它展示了如何执行Son:

using Newtonsoft.Json.Linq;

JObject sub = JObject.Parse(@"{ ““test””: { "“test1"”: true, "“test2"”: { ““test3"”: [1, 2, 3] } } }”);

JObject dom = JObject.Parse(@"{ ““test””: { "“test2"”: null, "“test3"”: ““string”” }, ““test2"”: ““newValue”” }”);

// Merge the two JSONs using Merge method 
JObject merged = dom.Merge(sub, new JsonMergeSettings() {  = MergeArrayHandling.Keep, ReplaceNullValuesWith = null });

// Convert the result to string for visualization:
string result = JsonConvert.SerializeObject(merged);

// Print the result Console.WriteLine(result);
// output:
// { “test”: { “test1”: true, “test2”: null, “test3”: “string” }, “test2”: “newValue” }

Csharp相关问答推荐

System.文本.Json现在总是需要无参数构造函数吗?

找不到网址:https://localhost:7002/Category/Add?区域= Admin.为什么我的URL是这样生成的?area = Admin而不是/Admin/

NumPy s fftn in C#with pythonnet'

如果存在对CodeAnalysis.CSharp的引用,则不能引用netStandard2.0库

将XPS转换为PDF C#

如何注册接口类型,类型<>

MongoDB.NET-将数据绑定到模型类,但无法读取整数值

如何使datagridview的列具有响应性,以便不是所有列都更改其宽度

未找到任何HTTP触发器.成功部署Azure Functions Project后(c#)

NET8 Maui&;iOS:AppCenter崩溃错误

使用带有参数和曲面的注入失败(&Q;)

TagHelpers在新区域不起作用

如何在CSharp中将json字符串转换为DataTable?

EF核心新验证属性`DeniedValues`和`StringCompison`不起作用

如何在GRPC代码First服务的返回类型上使用多态性?

.NET Google Workspace API获取错误CS0266

如何使用IHostedService添加数据种子方法

将两个for循环更改为一条LINQ语句

仅在Blazor Web App中覆盖生产的基本路径(.NET8中的_Hosts.cshtml文件功能?)

如何在特定时间间隔运行多个后台任务?