"EF BB BF"指的是"EF BB BF".在Visual Studio中创建的JSON文件的开头 [英] "EF BB BF" at the beginning of JSON files created in Visual Studio

查看:207
本文介绍了"EF BB BF"指的是"EF BB BF".在Visual Studio中创建的JSON文件的开头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一个项目中有一堆JSON文件设置为Embedded resource.我正在使用Newtonsoft.Json解析这些文件:

I have a bunch of JSON files set as Embedded resource in one of my projects. I'm using Newtonsoft.Json to parse these files:

public static string ReadStringFromStream(string streamName)
{
    using (System.IO.Stream stream = new EmbeddedResourceReader().GetType().Assembly.GetManifestResourceStream(streamName))
    {
        byte[] result = new byte[stream.Length];
        stream.Read(result, 0, (int)stream.Length);
        var str = Encoding.UTF8.GetString(result);
        return str;
    }
}
...

var traits = JsonConvert.DeserializeObject<Genre[]>(EmbeddedResourceReader.ReadStringFromStream("LNTCore.Genres.json"));
Genres = traits;

这将在Newtonsoft.Json中引发异常,因为它无法解析文件的开头.在这种情况下,最佳做法是什么?我应该如何处理这种情况?

This throws an exception in Newtonsoft.Json because it can't parse the beginning of the file. What's the best practice in this case? How should I be handling this sort of situations?

谢谢!

推荐答案

这是字节顺序标记(BOM).

That's a byte-order mark (BOM).

我假设您的第一个代码块显示了如何获取文件.如果希望UTF-8中的文件没有BOM,则可以使用 UTF8Encoding 构造函数以构建没有BOM的编码实例:

I'm assuming your first code block is showing how you get the file. If you want the files in UTF-8 without a BOM, you can use the UTF8Encoding constructor to build an encoding instance without a BOM:

var str = new UTF8Encoding(false).GetString(result);

这篇关于"EF BB BF"指的是"EF BB BF".在Visual Studio中创建的JSON文件的开头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆