gpt4 book ai didi

c# - 将 JSON 字符串添加到 C# 中的现有字符串

转载 作者:行者123 更新时间:2023-12-03 16:02:13 25 4
gpt4 key购买 nike

我正在尝试向现有字符串添加 JSON 字符串,但仍然无法成功。

这是原始字符串:originalJSONString

{
"properties": [
"property1",
"property2"
]
}

我想将此添加到原始字符串中: JSONStringIwantToAdd
{
"filter": {
"Name": "some filter name",
"Parameters": {
"LookupKey": "somekey",
"LookupValue": "somevalue"
}
}
}

要生成这样的结果字符串: finalJSONString
{
"properties": [
"property1",
"property2"
],
"filter": {
"Name": "some filter name",
"Parameters": {
"LookupKey": "somekey",
"LookupValue": "somevalue"
}
}
}

到目前为止,这是我的方向,但我在 propertiesJObject 中为空并且事后想不通。

这甚至是我要去的正确方向吗?
        var originalJObj = JObject.Parse(originalJSONString);
var tobeaddedJObj = JObject.Parse(JSONStringIwantToAdd);
var propertiesJObject = originalJObj["properties"] as JObject;
propertiesJObject.Add(tobeaddedJObj);
var serializer = new JsonSerializer { ContractResolver = new CamelCasePropertyNamesContractResolver() };
var finalJSONString = JObject.FromObject(originalJObj, serializer).ToString();

有人可以帮我解决这个问题吗?

感谢您的时间!

最佳答案

JSON.NET 包含的功能可以完全满足您的需求:JContainer.Merge

请注意, Merge 会修改原始对象,而不是返回一个新对象:

var original = JObject.Parse(@"{
""properties"": [
""property1"",
""property2""
]
}");

var toAdd = JObject.Parse(@"{
""filter"": {
""Name"": ""some filter name"",
""Parameters"": {
""LookupKey"": ""somekey"",
""LookupValue"": ""somevalue""
}
}
}");

original.Merge(toAdd, new JsonMergeSettings
{
// union array values together to avoid duplicates
MergeArrayHandling = MergeArrayHandling.Union
});

fiddle 链接: https://dotnetfiddle.net/o51GuA

关于c# - 将 JSON 字符串添加到 C# 中的现有字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62292075/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com