如何在现有json中添加属性



我收到一个JSON文件,如下所示:

{
"Name": "testeName",
"type": "unique",
"TestData": [{
"price": 2.3
}]
}

我想给TestData中的每个对象添加一个新的属性("type":"unique"(,最后如下所示:

{
"Name": "testeName",
"type": "unique",
"TestData": [{
"price": 2.3,
"type": "unique"
}]
}

有什么方法可以用更少的代码做到这一点吗?我尝试了这个,但有很多代码,我相信一定有一个更简单的方法:

using (MemoryStream memoryStream1 = new MemoryStream())
{
using (Utf8JsonWriter utf8JsonWriter1 = new Utf8JsonWriter(memoryStream1))
{
using (JsonDocument jsonDocument = JsonDocument.ParseValue(ref reader))
{
utf8JsonWriter1.WriteStartObject();
foreach (var element in jsonDocument.RootElement.EnumerateObject())
{
if (element.Name == "price")
{
// Copying existing values from "TestData" object
foreach (var testDataElement in element.Value.EnumerateArray())
{
utf8JsonWriter1.WritePropertyName(element.Name);
// Staring new object
utf8JsonWriter1.WriteStartObject();
// Adding "Name" property
utf8JsonWriter1.WritePropertyName("type");
utf8JsonWriter1.WriteStringValue("unique");
//System.InvalidOperationException : 'Cannot write the start of an object or array without a property name. Current token type is 'String'.'
testDataElement.WriteTo(utf8JsonWriter1); 
}
utf8JsonWriter1.WriteEndObject();
}
else
{
element.WriteTo(utf8JsonWriter1);
}
}
utf8JsonWriter1.WriteEndObject();
}
}
var resultJson = Encoding.UTF8.GetString(memoryStream1.ToArray());
}

您可以尝试此代码

using Newtonsoft.Json;
var jsonObject = JObject.Parse(json);
var testDataObj =  (JObject) ((JArray)jsonObject["TestData"])[0];

testDataObj.Add("type", "unique");
json=jsonObject.ToString();

结果

{
"Name": "testeName",
"type": "unique",
"TestData": [
{
"price": 2.3,
"type": "unique"
}
]
}

您可以使用Newtonsoft JSON Nuget包吗?

您可以从文件中读取JSON,然后使用JObject.Add方法为JSON对象添加属性和值:

using (StreamReader file = File.OpenText("[insert your file path here]"))
using (JsonTextReader jtReader = new JsonTextReader(file))
{
JObject jObj = (JObject)JToken.ReadFrom(reader);
jObj.Add("type", "unique");
}

在.NET 6及更高版本中,您可以使用新的JsonNode可编辑JSON文档对象模型来加载、修改和重新序列化您的JSON:

// Load the file
JsonObject root;
using (var stream = File.OpenRead(inputFileName))
{
root = (JsonNode.Parse(GetJson()) ?? new JsonObject()).AsObject();
}
// Add "type" to "TestData[*]"
if (root["TestData"] is JsonArray array)
{
foreach (var obj in array.OfType<JsonObject>())
{
obj["type"] = "unique";
}
}
//Examine the resulting JSON string
var resultJson = root.ToString();
//Or write back the file directly, without using an intermediate JSON string
using (var stream = File.Create(outputFileName))
using (var writer = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true }))
{
root.WriteTo(writer);
}

在这里演示小提琴。

相关内容

  • 没有找到相关文章

最新更新