“EF BB BF” at the beginning of JSON files created in Visual Studio

…衆ロ難τιáo~ 提交于 2019-12-30 08:25:33

问题


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;

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?

Thanks!


回答1:


That's a byte-order mark (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);



回答2:


Change the encoding of the file - when saving there is a little down arrow that lets you go to advanced saving options, including the encoding.

What you are seeing is the BOM (Byte Order Mark) - it indicates this is a Unicode file (UTF-8 in this case, I believe).

You can also just strip it, which should let it parse without issue.

This is something that is best just dealt with once, when saving the file than repeatedly fixing in code.



来源:https://stackoverflow.com/questions/44098326/ef-bb-bf-at-the-beginning-of-json-files-created-in-visual-studio

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!