一个.json格式的Json文件用记事本打开,修改某个值后保存,然后利用Newtonsoft.Json 转成对象时报错了。报错信息如题:

Unexpected character encountered while parsing value: .Path ''

  public static T ToObject<T>(this string Json)
        {
            return Json == null ? default(T) : JsonConvert.DeserializeObject<T>(Json);
        }

 错误原因可能是下面这个原因引起的:

另存为:UFT-8就好了,记住用什么编码保存,就用什么编码解析,但有的windows系统用记事本打开保存为UTF-8时模板带有BOM头(Byte Order Mark:字节序标记),文件读取转成byte[] 时,首部位置有固定的编码:EF BB BF。为了防止这类情况发生,需要做一个判断,去除BOM头就可以了。

json
适用于现代 C++ 的 JSON。

例如:

  using (FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read))
                {
                    byte[] data = new byte[fs.Length];
                    fs.Read(data, 0, data.Length);
                    byte[] bomBuffer = new byte[] { 0xef, 0xbb, 0xbf };
                    string dataStr = System.Text.Encoding.UTF8.GetString(data);
                    if (data[0] == bomBuffer[0]
                        && data[1] == bomBuffer[1]
                        && data[2] == bomBuffer[2])
                    {
                        int copyLength = data.Length - 3;
                        byte[] dataNew = new byte[copyLength];
                        Buffer.BlockCopy(data, 3, dataNew, 0, copyLength);
                        dataStr = System.Text.Encoding.UTF8.GetString(dataNew);
                    }
                     
                    var nameKeys = dataStr.ToObject<List<KeyValueData>>();                    
                }

例如把程序中运行的配置项做一个如下的界面来管理,保存为Json格式,还是很方便的。 

 

 

 

阅读全文
AI总结
GitHub 加速计划 / js / json
19
5
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:5 个月前 )
34665ae6 binary -> binary_t Signed-off-by: Robert Chisholm <robert.chisholm@sheffield.ac.uk> 7 天前
f3dc4684 Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3.28.9 to 3.28.10. - [Release notes](https://github.com/github/codeql-action/releases) - [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/github/codeql-action/compare/9e8d0789d4a0fa9ceb6b1738f7e269594bdd67f0...b56ba49b26e50535fa1e7f7db0f4f7b4bf65d80d) --- updated-dependencies: - dependency-name: github/codeql-action dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> 14 天前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐