【发布时间】:2019-10-09 10:51:57
【问题描述】:
{
"TestData":{
"Year__of__Account":"2019",
"Tax___x0025_":"0.06",
"Buildings__1":"1000",
"Contents__1":"400",
"Total_Insurable_Value":"100",
"Buildings__Prem":"2560.8",
"Contents__Prem":"1707.2",
"YB__1":"1950",
"No__Buildings":"55",
"Location_Sprinklers_YN":"No",
"test":"test"
}
}
在上面的示例 JSON 中,我想在属性“TestData”中添加一个名为“Name”的属性,其值为“John”。如何使用 .net Core 3.0 System.Text.Json 库来实现这一点。
我曾尝试使用 Utf8JsonWriter 的方法,但它正在创建一个新的 JSON 对象,而不是将其附加到上述现有 JSON 中。
using (MemoryStream memoryStream1 = new MemoryStream())
{
using (Utf8JsonWriter utf8JsonWriter1 = new Utf8JsonWriter(memoryStream1))
{
using (JsonDocument jsonDocument = JsonDocument.Parse(json))
{
utf8JsonWriter1.WriteStartObject();
utf8JsonWriter1.WritePropertyName("Name");
utf8JsonWriter1.WriteStringValue("John");
utf8JsonWriter1.WriteEndObject();
// how can I add above properties to JsonDocument object??
}
}
}
【问题讨论】:
-
我个人还没有开始安装 VS2019/Core3,所以我自己没有这样做,但大概你会使用
JsonDocument.Parse()加载文档,就像你一样,添加新属性,然后用JsonDocument.WriteTo()写出来。 -
是的,正是我的问题是如何在加载 JsonDocument 后添加新属性?我在他们的文档中找不到任何方法。
-
JsonDocument是只读的。有一个未解决的问题Writable Json DOM #39922 跟踪此问题。相关但不重复:Modifying a JSON file using System.Text.Json. -
你能解决这个问题吗?我在指定位置插入属性时遇到问题,所以想知道您是否可以通过以下question 提供帮助。我可以同时使用 Newtonsoft 或 System.Text.Json。
-
您无法使用 System.Text.Json 添加属性。使用 Newtonsoft JObject 将属性添加到您的 Json 对象。参考这个->JObject
标签: c# json .net-core-3.0 system.text.json