System.Text.Json 合并两个对象 [英] System.Text.Json Merge two objects

查看:37
本文介绍了System.Text.Json 合并两个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将这样的两个 json 对象与 System.Text.Json 合并?

Is it possible to merge two json objects like this with System.Text.Json?

对象 1

{
   id: 1
   william: "shakespeare"
}

对象 2

{
   william: "dafoe"
   foo: "bar"
}

结果对象

{
    id: 1
    william: "dafoe"
    foo: "bar"
}

我可以像这样用 newtonsoft.json 实现它

I am able to achieve it with newtonsoft.json like this

var obj1 = JObject.Parse(obj1String);
var obj2 = JObject.Parse(obj2String);

obj1.Merge(obj2);
result = settings.ToString();

但是有没有System.Text.Json的方法?

推荐答案

自 .Net Core 3.0 起,System.Text.Json:

  • There are no Merge or Populate methods on JsonDocument.

JsonSerializer.

There are no Merge or Populate methods on JsonSerializer.

更一般地,JsonDocument只读.它

提供一种机制,用于检查 JSON 值的结构内容,而无需自动实例化数据值.

Provides a mechanism for examining the structural content of a JSON value without automatically instantiating data values.

因此,它不支持以任何方式修改 JSON 值,包括将另一个 JSON 值合并到其中.

As such it isn't designed to support modifying a JSON value in any way including merging another JSON value into it.

目前有一个增强请求来实现一个可修改的 JSON 文档对象模型:问题 #39922:可写 Json DOM.它有一个相关的规范System.Text.Json 的可写 JSON 文档对象模型 (DOM).如果实现此增强功能,JSON 文档的合并将成为可能.您可以添加一个问题,请求功能等效于 JContainer.Merge(),作为先决条件链接回问题#39922.

There is currently an enhancement request to implement a modifiable JSON Document Object Model: Issue #39922: Writable Json DOM. It has an associated specification Writable JSON Document Object Model (DOM) for System.Text.Json. If this enhancement were implemented, merging of JSON documents would become possible. You could add an issue requesting functionality equivalent to JContainer.Merge(), linking back to Issue #39922 as a prerequisite.

这篇关于System.Text.Json 合并两个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆