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

前端 未结 3 519
故里飘歌
故里飘歌 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:54

    One of the options would be to parse json into JObject and add property to it via Newtonsoft's Json.NET:

    var obj = JObject.Parse("{'key':'value'}");
    obj.Add("required", true);
    Console.WriteLine(obj); // { "key": "value", "required": true }
    

    To add new object you can use this overload of Add:

    obj.Add("validate", JObject.FromObject(new { required = true }));
    

    So the whole solution will look something like this:

    var obj = JObect.Parse(your_json);
    
    foreach(var token in obj.DescendantsAndSelf().ToList()) // ToList is important!!!
    {
        if(token is JObject xObj)
        {
            // check your conditions for adding property
            // check if object does not have "validate" property
            if(satisfies_all_conditions)
            {
                xObj.Add("validate", JObject.FromObject(new { required = true }));
            }
        }
    }
    

提交回复
热议问题