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

如何在运行时将属性添加到JSON(C#),c#,json,asp.net-mvc,json.net,runtime,C#,Json,Asp.net Mvc,Json.net,Runtime,注意:我正在使用System.Text.Json包 下面是我从数据库获得的JSON。我必须检查JSON中的每个键,并检查键名中是否有句点();如果是这样,我需要在JSON中添加一个值为true的属性required,以提供运行时验证: validate:{"required", true} 这是我的JSON: { "display": "wizard", "settings": {}, "components": [{ "title": "Event I

注意:我正在使用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
    }]
} 
{
“显示”:“向导”,
“设置”:{},
“组成部分”:[{
“标题”:“活动信息”,
“标签”:“事件信息”,
“类型”:“面板”,
“密钥”:“事件信息”,
“组成部分”:[{
“标签”:“行1列”,
“栏目”:[{
“组成部分”:[{
“标签”:“活动日期”,
“格式”:“dd/MM/yyyy hh:MM a”,
“tableView”:错误,
“日期选择器”:{
“残疾周末”:错误,
“禁止工作日”:false
},
“验证”:{
“独特”:真实
},
“键”:“Event.EventDate”,
“类型”:“日期时间”,
“输入”:正确,
“后缀”:“,
“小部件”:{
“类型”:“日历”,
“displayInTimezone”:“查看器”,
“语言”:“en”,
“useLocaleSettings”:false,
“allowInput”:正确,
“模式”:“单一”,
“使能时间”:正确,
“noCalendar”:错,
“格式”:“dd/MM/yyyy hh:MM a”,
“小时增量”:1,
“分钟增量”:1,
“时间24小时”:假,
“minDate”:空,
“残疾周末”:错误,
“禁止工作日”:false,
“maxDate”:空
}
}],
“宽度”:6,
“偏移量”:0,
“推送”:0,
“拉动”:0
}, {
“组成部分”:[{
“标签”:“持续时间(分钟)”,
“面具”:假,
“拼写检查”:正确,
“tableView”:错误,
“分隔符”:false,
“要求的CIMAL”:错误,
“inputFormat”:“普通”,
“密钥”:“事件持续时间”,
“类型”:“编号”,
“输入”:真
}],
“宽度”:6,
“偏移量”:0,
“推送”:0,
“拉动”:0
}],
“tableView”:错误,
“键”:“行1列”,
“类型”:“列”,
“输入”:错误
}, {
“标签”:“第2列”,
“栏目”:[{
“组成部分”:[{
“标签”:“事件类别”,
“小部件”:“choicesjs”,
“tableView”:没错,
“dataSrc”:“自定义”,
“数据”:{
“自定义”:“值=getEventCategoryValues()”
},
“valueProperty”:“AgencyEventCategoryId”,
“模板”:“{item.text}}”,
“选择阈值”:0.3,
“验证”:{
“必需”:true
},
“键”:“Event.AgencyEventCategoryId”,
“类型”:“选择”,
“indexeddb”:{
“筛选器”:{}
},
“输入”:真
}],
“宽度”:6,
“偏移量”:0,
“推送”:0,
“拉动”:0
}, {
“组成部分”:[{
“标签”:“出席人数”,
“小部件”:“choicesjs”,
“tableView”:没错,
“多重”:假,
“dataSrc”:“自定义”,
“数据”:{
“自定义”:“值=getAttendanceValues()”
},
“valueProperty”:“AgencyEventAttendanceId”,
“模板”:“{item.text}}”,
“选择阈值”:0.3,
“验证”:{
“必需”:正确,
},
“键”:“Event.AgencyEventAttendanceId”,
“类型”:“选择”,
“indexeddb”:{
“筛选器”:{}
},
“输入”:真
}],
“宽度”:6,
“偏移量”:0,
“推送”:0,
“拉动”:0
}],
“tableView”:错误,
“键”:“行2列”,
“类型”:“列”,
“输入”:错误
}, {
“标签”:“事件选项”,
“小部件”:“choicesjs”,
“tableView”:没错,
“多重”:没错,
“dataSrc”:“自定义”,
“数据”:{
“自定义”:“值=GetEventManagerValue(data.Event.AgencyEventCategoryId)”
},
“模板”:“{item.text}}”,
“refreshOn”:“Event.AgencyEventCategoryId”,
“clearOnRefresh”:正确,
“选择阈值”:0.3,
“calculateServer”:false,
“验证”:{
“必需”:正确,
“多重”:正确
},
“键”:“Event.EventDetail”,
“类型”:“选择”,
“indexeddb”:{
“筛选器”:{}
},
“输入”:真
}, {
“标签”:“案例说明”,
“所见即所得”:没错,
“自动扩展”:正确,
var obj = JObject.Parse("{'key':'value'}");
obj.Add("required", true);
Console.WriteLine(obj); // { "key": "value", "required": true }
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
            }
        }

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