You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#实现JSON数字验证函数存在测试用例冲突问题求助

解决C# IsJsonNumber函数的指数验证与基础数字冲突问题

先明确JSON官方规范里的数字结构:

JSON数字必须符合:可选负号 + 整数部分(0或非零开头的数字串) + 可选小数部分(.后跟至少一个数字) + 可选指数部分(e/E后跟可选±号,再跟至少一个数字)

你的问题核心是:原函数要么没严格校验指数部分的完整性(比如"22e"这种无后续数字的情况误判为合法),要么修复时错误地把指数部分变成了必填项,导致纯整数(如"0""70")被误判为非法。

修正后的IsJsonNumber实现

public static bool IsJsonNumber(string input)
{
    if (string.IsNullOrWhiteSpace(input))
        return false;

    int index = 0;

    // 处理可选的负号
    if (input[index] == '-')
        index++;

    // 处理整数部分:要么是单个0,要么是非零开头的数字串
    if (index >= input.Length)
        return false;

    if (input[index] == '0')
    {
        index++;
        // 0后面不能直接跟其他数字(比如"012"不合法)
        if (index < input.Length && char.IsDigit(input[index]))
            return false;
    }
    else if (char.IsDigit(input[index]))
    {
        // 非零开头,读取所有后续数字
        while (index < input.Length && char.IsDigit(input[index]))
            index++;
    }
    else
    {
        // 整数部分既不是0也不是数字,直接非法
        return false;
    }

    // 处理可选的小数部分
    if (index < input.Length && input[index] == '.')
    {
        index++;
        // 小数点后面必须至少有一个数字
        if (index >= input.Length || !char.IsDigit(input[index]))
            return false;
        // 读取所有后续小数数字
        while (index < input.Length && char.IsDigit(input[index]))
            index++;
    }

    // 处理可选的指数部分
    if (index < input.Length && (input[index] == 'e' || input[index] == 'E'))
    {
        index++;
        // 指数后面可以跟可选的±号
        if (index < input.Length && (input[index] == '+' || input[index] == '-'))
            index++;
        // 指数符号后面必须至少有一个数字,否则不合法
        if (index >= input.Length || !char.IsDigit(input[index]))
            return false;
        // 读取所有后续指数数字
        while (index < input.Length && char.IsDigit(input[index]))
            index++;
    }

    // 所有字符都处理完才是合法的
    return index == input.Length;
}

关键修复说明

  • 拆分逻辑分层校验:把整数、小数、指数部分拆成独立的校验块,互不干扰。基础数字(无小数、无指数)会在走完整数部分后,直接进入最后一步的长度校验,返回true。
  • 指数部分强制完整性:当检测到e/E时,先处理可选的符号,然后必须存在至少一个数字才继续,否则直接返回false,完美拦截"22e""22e+""23E-"这类不完整的指数格式。
  • 严格遵循JSON规范:比如禁止"012"这种前导零的数字,符合json.org的要求。

测试用例验证

合法数字(应返回true)

  • "0"、"7"、"70"
  • "-123"、"123.456"
  • "123e4"、"123E+4"、"-123e-4"

非法数字(应返回false)

  • "22e"、"22e+"、"23E-"
  • "012"、"123."、".123"
  • "abc"、"12e"、"12+"

这样既解决了指数不完整的校验问题,又保证了基础数字的正确性。

内容的提问来源于stack exchange,提问作者Raluca123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 14:15:18