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

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

    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.

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

提交回复
热议问题