json.net反序列化抛出异常时,JSON是从项目资源加载 [英] json.net deserialization throwing exception when json is loaded from project resource
问题描述
这是产生问题的反序列化:
This is the deserialization that produces the problem:
public MyType ProblematicDeserialization(jsonString)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<MyType>(jsonString);
}
它的工作原理,或不deppending上jsonString的加载方式:
It works or it doesn't deppending on how jsonString is loaded:
案例1:
myObjectType
连载与json.net作为一个字符串,然后写入文件路径
:
myObjectType
serialized with json.net as a string and then written into filePath
:
//This line works correctly:
dynamic correctlyWorkingJson = IO.File.ReadAllText(filePath, Text.Encoding.UTF8);
CASE 2
相同的 CASE 1 ,但含量文件路径
已被复制,然后粘贴到我的项目一个JSON资源:
Same as CASE 1, but the content of filePath
has been copied and then pasted into a json resource in my project:
//This line gives an ERROR: ""Unexpected character encountered while parsing value: . Path '', line 0, position 0."
dynamic notWorkingJson = GetJsonFromResource(resourceName);
private string GetJsonFromResource(string resourceName)
{
byte[] jsonBytes = Convert.ToByte(ResourcesManager.GetResource(resourceName));
if (jsonBytes == null) {
throw new Exception(string.Format("Resource '{0}.json' was not found.", resourceName));
}
string json = UTF8BytesToString(jsonBytes);
return json;
}
在调试器,无论是 correctlyWorkingJson
和 notWorkingJson
看完全一样的,但显然是有东西让为json.net反序列化不能接受的资源JSON。
On the debugger, both correctlyWorkingJson
and notWorkingJson
look exactly the same, but obviously there is something that makes the resource json not acceptable for the json.net deserialization.
推荐答案
在/ U / DBC的评论,该字节序列表明,资源文件的编码是UTF-8-BOM,我解决了这种方式:
After /u/dbc's comment that the byte sequence indicated that the encoding of the resource file was UTF-8-BOM, I solved it this way:
- 我去盘源文件在我的项目当作一个资源
- 我用记事本++
- 编码编辑它 - >转换为UTF-8
之后,贴在原岗位完全相同的代码工作完美。
After that, the exact same code posted in the original post worked perfectly.
这篇关于json.net反序列化抛出异常时,JSON是从项目资源加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!