【发布时间】:2017-06-15 17:06:03
【问题描述】:
我有一个格式如下的 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"];
}
}
}
}
【问题讨论】:
-
用
obj["attributes"].Add("newFlag", isCostValuable);替换最内部的foreach循环