如何在运行时将属性添加到 JSON (C#)

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

注意:我正在使用 System.Text.Json 包 下面是 JSON 我从数据库中获取的信息。我必须遍历 JSON 中的每个键并检查键名中是否有句点 (.);如果是这样,我需要在 JSON 中添加值为 true 的 属性 required 以提供运行时验证:

validate:{"required", true}

这是我的JSON:

{
    "display": "wizard",
    "settings": {},
    "components": [{
        "title": "Event Information",
        "label": "Event Information",
        "type": "panel",
        "key": "EventInformation",
        "components": [{
            "label": "Row1Columns",
            "columns": [{
                "components": [{
                    "label": "Event Date",
                    "format": "dd/MM/yyyy hh:mm a",
                    "tableView": false,
                    "datePicker": {
                        "disableWeekends": false,
                        "disableWeekdays": false
                    },
                    "validate": {
                        "unique": true
                    },
                    "key": "Event.EventDate",
                    "type": "datetime",
                    "input": true,
                    "suffix": "<i ref=\"icon\" class=\"fa fa-calendar\" style=\"\"></i>",
                    "widget": {
                        "type": "calendar",
                        "displayInTimezone": "viewer",
                        "language": "en",
                        "useLocaleSettings": false,
                        "allowInput": true,
                        "mode": "single",
                        "enableTime": true,
                        "noCalendar": false,
                        "format": "dd/MM/yyyy hh:mm a",
                        "hourIncrement": 1,
                        "minuteIncrement": 1,
                        "time_24hr": false,
                        "minDate": null,
                        "disableWeekends": false,
                        "disableWeekdays": false,
                        "maxDate": null
                    }
                }],
                "width": 6,
                "offset": 0,
                "push": 0,
                "pull": 0
            }, {
                "components": [{
                    "label": "Duration (minutes)",
                    "mask": false,
                    "spellcheck": true,
                    "tableView": false,
                    "delimiter": false,
                    "requireDecimal": false,
                    "inputFormat": "plain",
                    "key": "Event.Duration",
                    "type": "number",
                    "input": true
                }],
                "width": 6,
                "offset": 0,
                "push": 0,
                "pull": 0
            }],
            "tableView": false,
            "key": "row1Columns",
            "type": "columns",
            "input": false
        }, {
            "label": "Row2Columns",
            "columns": [{
                "components": [{
                    "label": "Event Category",
                    "widget": "choicesjs",
                    "tableView": true,
                    "dataSrc": "custom",
                    "data": {
                        "custom": "values = getEventCategoryValues()"
                    },
                    "valueProperty": "AgencyEventCategoryId",
                    "template": "<span>{{ item.text }}</span>",
                    "selectThreshold": 0.3,
                    "validate": {
                        "required": true
                    },
                    "key": "Event.AgencyEventCategoryId",
                    "type": "select",
                    "indexeddb": {
                        "filter": {}
                    },
                    "input": true
                }],
                "width": 6,
                "offset": 0,
                "push": 0,
                "pull": 0
            }, {
                "components": [{
                    "label": "Attendance",
                    "widget": "choicesjs",
                    "tableView": true,
                    "multiple": false,
                    "dataSrc": "custom",
                    "data": {
                        "custom": "values = getAttendanceValues()"
                    },
                    "valueProperty": "AgencyEventAttendanceId",
                    "template": "<span>{{ item.text }}</span>",
                    "selectThreshold": 0.3,
                    "validate": {
                        "required": true,
                    },
                    "key": "Event.AgencyEventAttendanceId",
                    "type": "select",
                    "indexeddb": {
                        "filter": {}
                    },
                    "input": true
                }],
                "width": 6,
                "offset": 0,
                "push": 0,
                "pull": 0
            }],
            "tableView": false,
            "key": "row2Columns",
            "type": "columns",
            "input": false
        }, {
            "label": "Event Options",
            "widget": "choicesjs",
            "tableView": true,
            "multiple": true,
            "dataSrc": "custom",
            "data": {
                "custom": "values = getEventManagerValues(data.Event.AgencyEventCategoryId)"
            },
            "template": "<span>{{ item.text }}</span>",
            "refreshOn": "Event.AgencyEventCategoryId",
            "clearOnRefresh": true,
            "selectThreshold": 0.3,
            "calculateServer": false,
            "validate": {
                "required": true,
                "multiple": true
            },
            "key": "Event.EventDetail",
            "type": "select",
            "indexeddb": {
                "filter": {}
            },
            "input": true
        }, {
            "label": "Casenote",
            "wysiwyg": true,
            "autoExpand": true,
            "spellcheck": true,
            "tableView": true,
            "calculateServer": false,
            "key": "Event.EventCasenote[0].Casenote",
            "type": "textarea",
            "input": true
        }],
        "input": false,
        "tableView": false,
        "breadcrumbClickable": true,
        "buttonSettings": {
            "previous": true,
            "cancel": true,
            "next": true
        },
        "collapsible": false
    }]
} 

其中一个选项是将 json 解析为 JObject 并通过 Newtonsoft 的 Json.NET:

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

要添加新对象,您可以使用 Add 的重载:

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

所以整个解决方案看起来像这样:

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

这对我来说是个有趣的任务,所以这就是我写的

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

    }
}

此代码将添加每个对象 属性 "required" 如果它不存在。 您只需要添加 Validation 方法并在 if 块中调用它。 如果 "required" 属性 存在

,最好添加不会继续检查所有属性的额外验证

我遇到了 ,并且找到了解决方案,请参阅下面的代码和注释。虽然我正在使用 Newtonsoft,但值得检查您是否可以使用 Newtonsoft 库并且尚未找到 System.Text.Json.

的解决方案

JSON 中的所有控件都是组件 object/array 的一部分,因此我们可以使用 JSONPath,请参阅 link 了解更多 details

public void IterateJson(JObject obj, string mandatoryFieldKey)
        {
JToken jTokenFoundForMandatoryField = obj.SelectToken
("$..components[?(@.key == '" + mandatoryFieldKey + "')]");   
            //Now we convert this oken into an object so that we can add properties/objects in it
            if (jTokenFoundForMandatoryField is JObject jObjectForMandatoryField)
            {
                //We check if validate already exists for this field, if it does not
 //exists then we add validate and required property inside the if condition
                if (jObjectForMandatoryField["validate"] == null)
                    jObjectForMandatoryField.Add("validate", 
JObject.FromObject(new { required = true })); //add validate and required property
                else
                {
                    //If validate does not exists then code comes here and 
//we convert the validate into a JObject using is JObject statement
                    if (jObjectForMandatoryField["validate"] is JObject validateObject)
                    {
                        //We need to check if required property already exists, 
//if it does not exists then we add it inside the if condition.
                        if (validateObject["required"] == null)
                        {
                            validateObject.Add("required", true); //add required property
                        }
                    }
                }                
            }  
}