How to add properties at runtime to JSON (C#)

前端 未结 3 482
故里飘歌
故里飘歌 2021-01-25 14:52

Note: Im working with System.Text.Json package Below is JSON I am getting from a database. I have to go through each of the keys in the JSON and check if there is a period (

3条回答
  •  悲&欢浪女
    2021-01-25 15:48

    It was interesting task for me, so this is what i have written

    class Program
    {
        static void Main(string[] args)
        {
            string jsonFilePath = @"test.json"; //path to your json
            string json = File.ReadAllText(jsonFilePath);
            var data = JObject.Parse(json);
            CheckJson(data);
            Console.ReadLine();
        }
    
        static void CheckJson(JToken value)
        {
            if (value.Values().Count() != 0) //if more than 0 - so value is object or array and we have to call this method for each property
            {
                foreach (var item in value.Values().ToList())
                {
                    CheckJson(item);
                }
            }
            else if (true) //else - we have exactly value of key, which we can check, for example if . exists or additional checks
            {
                if (value.Parent.Parent is JObject jObject && jObject["validate"] == null) //check if above "required" property exists 
                {
                    jObject.Add("validate", JObject.FromObject(new { required = true })); //add required property
                }
            }
    
        }
    }
    

    This code will add in each object property "required" if it is not exists. All you need - just add Validation method and call it in if block. And better to add additional validation that won't continue checking all properties if "required" property exists

提交回复
热议问题