有时我们封装好的实体转化成的json字段的值和第三方要求的不一样,比如我们字段的值是字符串,我们需要使用int类型的值,就需要将这个键的值转化成int类型。
比如将以下 convulsionNumber字段中字符串的值“一次”替换为0
{"convulsionTypeName":"晕倒","convulsionNumber": "一次"}
方法如下:
        /// <summary>
         /// 查找json中指定节点的值,替换为指定的值
         /// </summary>
         /// <param name="json"></param>
         /// <param name="strPropertyName">节点名</param>
         /// <param name="strnew">替换成的新值</param>
         /// <returns></returns>
         public static string ReplaceStoInt(string json,string strPropertyName, int strnew)
         {
             string propertyName = strPropertyName;
                 //"convulsionNumber";
             int newValue = strnew; // 要替换的新值
                               // 构建匹配字符串的正则表达式
             string pattern = $"\"{propertyName}\":\\s*\"(.+?)\"";
            // 定义替换的内容
             string replacement = $"\"{propertyName}\": \"{newValue}\"";
             // 进行正则表达式替换
             string result = Regex.Replace(json, pattern, replacement);
             return result;
         }