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

NewtonSoft Json解析报错:含项目符号的JSON字符串处理问询

解决Newtonsoft.Json解析含项目符号JSON的报错问题

你碰到的这个问题,核心原因是JSON里的项目符号字符•和你代码里用来匹配的字符编码不匹配,或者读取文件时的编码问题导致字符变形,所以直接替换"•\t"没效果。下面给你几个靠谱的解决办法:

1. 先搞清楚项目符号的真实Unicode编码

很多符号看起来像•但编码完全不同(比如全角圆点、实心圆等),先加一段代码找出目标字符的真实编码:

string strFileContent = File.ReadAllText(JsonFilePath, Encoding.UTF8).Replace("\0", string.Empty);
foreach (char c in strFileContent)
{
    // 筛选可能的标点类符号,找到你的项目符号
    if (char.IsPunctuation(c) && c != '\t') 
    {
        Console.WriteLine($"字符: {c}, Unicode编码: 0x{(int)c:X4}");
    }
}

运行后就能拿到对应符号的编码(比如普通的•是0x2022)。

2. 用Unicode转义字符精准替换

拿到编码后,直接用Unicode转义字符替换,比字符串匹配可靠得多:

// 读取文件时指定UTF8编码,避免乱码
string strFileContent = File.ReadAllText(JsonFilePath, Encoding.UTF8).Replace("\0", string.Empty);

// 替换目标项目符号(这里用0x2022为例,换成你查到的编码)
strFileContent = strFileContent.Replace('\u2022', '-'); 
// 要是需要替换制表符,再加这行
strFileContent = strFileContent.Replace("\t", " ");

JObject reportLayout = JObject.Parse(strFileContent);

3. 通用替换所有常见项目符号

如果你不确定具体是哪个符号,用正则表达式一次性替换多种常见列表符号:

using System.Text.RegularExpressions;

string strFileContent = File.ReadAllText(JsonFilePath, Encoding.UTF8).Replace("\0", string.Empty);
// 替换•、●、■、○这些常见项目符号为短横线
strFileContent = Regex.Replace(strFileContent, @"[\u2022\u25CF\u25A0\u25CB]", "-");
strFileContent = strFileContent.Replace("\t", " ");

JObject reportLayout = JObject.Parse(strFileContent);

补充:为什么之前的替换失效?

你之前用Replace("•\t", ...)没效果,主要是两个原因:

  • 代码文件的编码和JSON文件的编码不一致,导致代码里的•和JSON里的不是同一个字符;
  • 读取JSON文件时没指定正确编码,字符被错误转义,导致匹配失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 13:47:27