小编Kun*_*til的帖子

如何使用 System.Text.Json 库在现有 json 中添加属性?

       {
          "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"
           }
        }
Run Code Online (Sandbox Code Playgroud)

在上面的示例 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??
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

c# json .net-core-3.0 system.text.json

11
推荐指数
2
解决办法
7513
查看次数

标签 统计

.net-core-3.0 ×1

c# ×1

json ×1

system.text.json ×1