gpt4 book ai didi

c# - 更新对象数组

转载 作者:行者123 更新时间:2023-11-30 23:11:42 26 4
gpt4 key购买 nike

我有一个具有以下格式的 json 文件:

{
"value": [
{
"ccCode": "1234",
"attributes": {
"ePCode": 23467
}
},
{
"ccCode": "1234",
"attributes": {
"ePCode": 23467
}
}
]
}

我简化了 json,但它在 attributes 属性中有更多的字段和更多的嵌套属性。我试图遍历值数组中的对象,并检索它的两个属性。基于这两个值,我将获取第三个值并将其作为附加属性添加到 attributes 属性中。所以最后我想要:

{
"value": [
{
"ccCode": "1234",
"attributes": {
"ePCode": 23467,
"newFlag": true
}


},
{
"ccCode": "1234",
"attributes": {
"ePCode": 23467,
"newFlag": false
}
}
]
}

我创建了下面的代码。到目前为止,我可以获取我感兴趣的属性。我的问题是尝试更新它。任何帮助将不胜感激。

string templateFile = @"C:\Users\template.json";
//rss
JObject template = JObject.Parse(File.ReadAllText(templateFile));

foreach (var record in template)
{
string name = record.Key;
JToken value = record.Value;
foreach(var obj in value)
{
//fetch two values from each json object,
//based on these , fetch a flag and then add it to the json object
var ep = obj["attributes"];
ep = ep["ePCode"].Value<int?>();
var cost = obj["ccCode"].ToString();
bool isCostValuable = isCostValuable((int)ep, cost);

///want to add a new property in the property attributes
//this is where I get stuck
foreach(JProperty prop in obj)
{
if (prop.Name == "attributes")
{
JObject first = (JObject)obj;
JArray item = (JArray)first["attributes"];
}
}
}
}

最佳答案

你非常接近,你只需要用 ep.Add( 调用替换最里面的 foreach 循环,然后你可以通过调用 template.ToString( );

string templateFile = @"C:\Users\template.json";
string outputFile = @"C:\Users\output.json";
//rss
JObject template = JObject.Parse(File.ReadAllText(templateFile));

foreach (var record in template)
{
string name = record.Key;
JToken value = record.Value;
foreach(var obj in value)
{
//fetch two values from each json object,
//based on these , fetch a flag and then add it to the json object
var ep = obj["attributes"];
ep = ep["ePCode"].Value<int?>();
var cost = obj["ccCode"].ToString();
bool isCostValuable = isCostValuable((int)ep, cost);

ep.Add("newFlag", isCostValuable);
}
}

File.WriteAllText(outputFile, templateFile.ToString());

关于c# - 更新对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44573141/

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