【问题标题】:Updating an array of objects更新对象数组
【发布时间】: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循环

标签: c# json json.net


【解决方案1】:

你离得很近,你只需要调用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());

【讨论】:

    【解决方案2】:

    如果你有更多的字段,你的代码就会变脏!!

    你可以遵循这个结构:

    首先,在 C# 中创建一些与 JSON 模型相同的类,例如:

    public class Attribute
    {
        public string ePCode { get; set; }
    }
    public class Container
    {
        public string ccCode { get; set; }
        public List<Attribute> attributes { get; set; }
    }
    public class ValueContainer
    {
        public List<Container> value { get; set; }
    }
    

    然后只需使用Json.NET 框架将它们转换在一起:

    Json.NET 是适用于 .NET 的流行的高性能 JSON 框架。 它是开源软件,完全免费

    ValueContainerdata = JsonConvert.DeserializeObject<ValueContainer>(templateFile);
    
    foreach (var item in x.value)
    {
        item.ccCode = "new ccCode";
        foreach (var attr in item.attributes)
        {
            attr.ePCode = "new ePCode";
        }
    }
    

    更新数据后,您可以简单地将其改回 JSON:

    var updatedJSON = JsonConvert.SerializeObject(data);
    

    【讨论】:

    • 你为什么推荐使用JavaScriptSerializer,然后包括文档中的说明你应该使用JavaScriptSerializer,而应该使用Json.NET。
    猜你喜欢
    • 2021-07-08
    • 2020-07-01
    • 2019-03-25
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    • 2021-04-29
    • 1970-01-01
    相关资源
    最近更新 更多