查找json中指定节点的值,替换为指定的值

有时我们封装好的实体转化成的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;
        }

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-17 15:00:03       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-17 15:00:03       72 阅读
  3. 在Django里面运行非项目文件

    2024-07-17 15:00:03       58 阅读
  4. Python语言-面向对象

    2024-07-17 15:00:03       69 阅读

热门阅读

  1. SpringBoot --附包扫描、自动装配原理(面试题)

    2024-07-17 15:00:03       20 阅读
  2. 常见的服务器存储安全威胁及应对措施

    2024-07-17 15:00:03       16 阅读
  3. Mybatis——配置之映射器说明

    2024-07-17 15:00:03       18 阅读
  4. Matlab课程设计——手指静脉识别项目

    2024-07-17 15:00:03       19 阅读
  5. 单片机编程分层思想APP BSP HAL 三层结构

    2024-07-17 15:00:03       23 阅读