如何在运行时将属性添加到JSON(C#) [英] How to add properties at runtime to JSON (C#)

查看:96
本文介绍了如何在运行时将属性添加到JSON(C#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 (.) in the key name; if so, I need to add a property required with the value of true in the JSON in order to provide runtime validation:

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

推荐答案

我正在

I was having similar issue, and have found a solution, see below the code and comments. I am using Newtonsoft though but it is worth checking if you can use Newtonsoft library and have not found a solution for System.Text.Json.

JSON中的所有控件都是组件对象/数组的一部分,因此我们可以使用JSONPath,有关更多信息,请参见链接.

All controls in your JSON are part of component object/array so we can use JSONPath, see the link for more 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
                        }
                    }
                }                
            }  
}   

这篇关于如何在运行时将属性添加到JSON(C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆