Michael Tucker
Michael Tucker

Reputation: 309

Update property in json file with C#

I'm looking to change a specific property for each json record in my json file. I'd like to change the "Completed" property to "true" when a method finishes executing.

My json file looks like:

{
  "LoanRecords": [
    {
      "LoanGUID": "{70dbec7e-5e94-460d-831c-0a5dc2d085e2}",
      "RecordDT": "2020-11-10T14:44:34.378Z",
      "Completed": "false",
      "Environment": "TEBE",
      "ProcessType": "RateLock"
    },
    {
      "LoanGUID": "{70dbec7e-5e94-460d-831c-0a5dc2d085e2}",
      "RecordDT": "2020-11-10T14:53:12.187Z",
      "Completed": "false",
      "Environment": "TEBE",
      "ProcessType": "RateLock"
    }
    ]
}

My C# code is the following:

    private void ExecuteEvent(object sender, ElapsedEventArgs e)
    {
            string fileRecord = File.ReadAllText(jsonfile);
            LoanRecordRoot LoanRecord = JsonConvert.DeserializeObject<LoanRecordRoot>(fileRecord);
            foreach (var rec in LoanRecord.LoanRecords)
            {
                if (rec.Completed == "false")
                {
                    bool recordModified = ManipulateEncompass(rec.LoanGUID, rec.ProcessType);
                    if (recordModified)
                    {
                        // What should I do here to update "rec.Completed" to "true"
                        // for this particular record and write it back to the json file
                        // for that specific entry?
                    }
                }
            }
            Console.WriteLine("Successfully manipulated records!");
        }

Is there a way to flip the "Completed" property to "true" for the specific record in my "foreach" iteration, and update the json file accordingly for that specific record? I am hoping to avoid reading the entire file, deserializing, changing the property then writing the entire content back to the json file, I'm looking to just flip that specific property for each record in my "foreach" loop. -- I hope that makes sense.

I've looked at similar questions, which seem close to what I'm looking for, but the examples I've seen don't reflect writing back to the json file specifically without overwriting the file contents -- unless this specific action isn't possible, or I'm failing to understand the entire process (highly possible.)

Ex of a solution that's close to what I'm looking for: How to update a property of a JSON object using NewtonSoft -- but doesn't seem to quite fit the bill for what I'm wanting to do.

Thank you in advance for any helpful leads!

Upvotes: 2

Views: 6912

Answers (4)

user17122298
user17122298

Reputation:

using Kitchen_Mini_Project.Constants;
using Kitchen_Mini_Project.Moduls;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Kitchen_Mini_Project.Services
{
    public class Update
    {
        public static void UpdateAnyProduct()
        {
            string readdedFile = File.ReadAllText(PathConst.ProductDBPath);

            IList<Restaurant> products = JsonConvert.DeserializeObject<IList<Restaurant>>(readdedFile);

            foreach (var product in products[0].FoodItems)
            {
                if (product.foodName == "Chicken Burrito")
                {
                    product.foodName = "Chicken Burrito is Update ha ha";
                }
            }

            var json = JsonConvert.SerializeObject(products, Formatting.Indented);
            File.WriteAllText(PathConst.ProductDBPath, json);
        }
    }
}

Upvotes: 1

sadegh salehi
sadegh salehi

Reputation: 37

1-install package Newtonsoft.Json https://learn.microsoft.com/en-us/nuget/consume-packages/install-use-packages-visual-studio

2-use

string json = File.ReadAllText("server_client _input.json");
        dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
        jsonObj["Bots"][0]["Password"] = "new password";
        string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);
        File.WriteAllText("settings.json", output);

(For Install package use of this page :https://www.newtonsoft.com/json)

Upvotes: -2

Mario Sandoval
Mario Sandoval

Reputation: 136

you need to save the complete JSON when you update a property of an element of the array

    static void Main(string[] args)
    {
        const string jsonPath = @"C:\Logs\recordRoot.json";
        var loanRecordRoot = JsonConvert.DeserializeObject<LoanRecordRoot>(File.ReadAllText(jsonPath));
        foreach (var record in loanRecordRoot.LoanRecords)
        {

            if (record.Completed == "false")
            {
                if (ManipulateEncompass(rec.LoanGUID, rec.ProcessType))
                {
                    record.Completed = "true";
                }
            }
        }

       //Save Json
       var json = JsonConvert.SerializeObject(loanRecordRoot, Formatting.Indented);
       File.WriteAllText(jsonPath, json);
    }

Upvotes: 2

Julius A
Julius A

Reputation: 39652

Looking at your JSON, it appears the "Completed" property is being serialized as of type string

Therefore, all you need to do is set it to "Completed": "true" within your condition in your snippet.

 if (recordModified)
 {
     rec.Completed = "true";
 }

At the end of your processing, simply serialize your LoanRecord object and write it back to your file.

Upvotes: 1

Related Questions