Adding a property into specified location into json using Newtonsoft.Json

后端 未结 1 1867
面向向阳花
面向向阳花 2020-12-22 07:50

I have a following JSON. I have added 2 x double quotes so that I could declare it as stringvariable in c#, in realit

1条回答
  •  臣服心动
    2020-12-22 08:33

    I have managed to fix this issue, posting a solution here in case it can help others. I have realised that all controls in my json are part of component object/array so we can use JSONPath, see the link for more details. Following code has done the trick:

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

    0 讨论(0)
提交回复
热议问题