joeCarpenter
joeCarpenter

Reputation: 1535

Updating an array of objects

I have a json file with the following format:

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

I simplified the json but it has a whole lot more of fields and more nested properties within attributes property. I'm trying to iterate through the objects in the value array, and retrieve two of its properties. Based on those two values I will fetch a 3rd value and want to add it to the attributes property as an additional prop. So in the end I want:

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


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

I created the code below. So far I can fetch my properties of interest. My problem is trying to update it. Any help will be greatly appreciated.

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"];
            }
        }
    }
}

Upvotes: 2

Views: 4330

Answers (2)

Majid Parvin
Majid Parvin

Reputation: 5012

If you have more fields your code going to be dirty!!

You can follow this structure:

First, make some Classes in C# same as your JSON model like:

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; }
}

then simply use Json.NET framework to convert these together:

Json.NET is a popular high-performance JSON framework for .NET. It is open source software and is completely free.

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";
    }
}

after that you've updated your data, you can simply change it back to JSON:

var updatedJSON = JsonConvert.SerializeObject(data);

Upvotes: 0

Scott Chamberlain
Scott Chamberlain

Reputation: 127563

You where quite close, you just need to replace the innermost foreach loop with a call to ep.Add( then you can save out your data with a call to 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());

Upvotes: 2

Related Questions