none
How to read and write a JSON file in C# RRS feed

  • Question

  • My JSON file called SchemaList.json looks like this:

    {
    "AuthenticateCmdlets" : "toyota/v1",
    "GetPowerState" : "toyota/v1/Engine",
    "PowerOff" : "toyota/v1/Engine",
    "PowerOn" : "toyota/v1/Engine",
    }

    I need help with reading the above file and then the user should be able
    to modify, say replace v1 with v2. Thanks a lot in advance,
    I am a beginner so kindly put some comments.
    using System;
    using System.Collections.Generic;
    using Newtonsoft.Json;
    using System.IO;
    namespace MySpace
    {
        class PrormaSC
        {
    
            public static void Main(string[] args)
            {
                LoadJson();
    
                Console.ReadLine();
            }
    
            public class SchemaInfo
            {
                public string AuthenticateCmdlets { get; set; }
                public string GetPowerState { get; set; }
                public string PowerOff { get; set; }
                public string PowerOn { get; set; }
            }
    
            public static void LoadJson()
            {
                using (StreamReader r = new StreamReader("SchemaList.json"))
                {
                    var json = r.ReadToEnd();
                    var items = JsonConvert.DeserializeObject<List<SchemaInfo>>(json);
                    foreach (var item in items)
                    {
                       // Console.WriteLine("{0} {1}", item.temp, item.vcc);
                    }
                }
            }
        }
    }
    
    Sunday, December 24, 2017 8:44 PM

Answers

  • Hello ananda,

    For a given json file.

    {
      "AuthenticateCmdlets": "toyota/v2",
      "GetPowerState": "toyota/v2/Engine",
      "PowerOff": "toyota/v2/Engine",
      "PowerOn": "toyota/v2/Engine"
    }

    You could replace the properties value by using JObject.(Of course you also could deserialize the json file into an object and then change property value, save all text to original document)

    public static void ReplaceJsonValue() { string filepath = "../../json1.json"; string result = string.Empty; using (StreamReader r = new StreamReader(filepath)) { var json = r.ReadToEnd(); var jobj = JObject.Parse(json); foreach (var item in jobj.Properties()) { item.Value = item.Value.ToString().Replace("v1", "v2"); } result = jobj.ToString(); Console.WriteLine(result); } File.WriteAllText(filepath, result); }

    The result

    Best regards,

    Neil Hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, December 25, 2017 2:04 AM
    Moderator

All replies

  • Hello ananda,

    For a given json file.

    {
      "AuthenticateCmdlets": "toyota/v2",
      "GetPowerState": "toyota/v2/Engine",
      "PowerOff": "toyota/v2/Engine",
      "PowerOn": "toyota/v2/Engine"
    }

    You could replace the properties value by using JObject.(Of course you also could deserialize the json file into an object and then change property value, save all text to original document)

    public static void ReplaceJsonValue() { string filepath = "../../json1.json"; string result = string.Empty; using (StreamReader r = new StreamReader(filepath)) { var json = r.ReadToEnd(); var jobj = JObject.Parse(json); foreach (var item in jobj.Properties()) { item.Value = item.Value.ToString().Replace("v1", "v2"); } result = jobj.ToString(); Console.WriteLine(result); } File.WriteAllText(filepath, result); }

    The result

    Best regards,

    Neil Hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, December 25, 2017 2:04 AM
    Moderator
  • This is very neat solution, thanks a bunch Neil, it works like a charm. Many thanks, happy holidays!!

    Let me share the full code so that someone searching can get the benefit of it:

    using System;
    using System.IO;
    using Newtonsoft.Json.Linq;
    
    namespace MySpace
    {
        class PrormaSC
        {
            static void Main()
            {
                RdWrJsonFile();
                Console.ReadLine();
            }
            public static void RdWrJsonFile()
            {
                string filepath = "SchemaList.json";
                string readResult = string.Empty;
                string writeResult = string.Empty;
                using (StreamReader r = new StreamReader(filepath))
                {
                    var json = r.ReadToEnd();
                    var jobj = JObject.Parse(json);
                    readResult = jobj.ToString();
                    foreach (var item in jobj.Properties())
                    {
                        item.Value = item.Value.ToString().Replace("v1", "v2");
                    }
                    writeResult = jobj.ToString();
                    Console.WriteLine(writeResult);
                }
                Console.WriteLine(readResult);
                File.WriteAllText(filepath, writeResult);
            }
        }
    }

    The json data file looks like this:

    {
      "AuthenticateCmdlets": "toyota/v2",
      "GetPowerState": "toyota/v2/Engine",
      "PowerOff": "toyota/v2/Engine",
      "PowerOn": "toyota/v2/Engine"
    }

    best regards

    ananda


    Monday, December 25, 2017 2:39 AM