这是产生问题的反序列化:
public MyType ProblematicDeserialization(jsonString)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<MyType>(jsonString);
}
它是否有效取决于 json 字符串的加载方式:
CASE 1:
myObjectType
用 json.net 序列化为字符串然后写入filePath
:
//This line works correctly:
dynamic correctlyWorkingJson = IO.File.ReadAllText(filePath, Text.Encoding.UTF8);
CASE 2
Same as CASE 1,但是内容filePath
已被复制并粘贴到我的项目中的 json 资源中:
//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
and notWorkingJson
看起来完全一样,但显然有一些东西使得资源 json 无法被 json.net 反序列化所接受。
经过/u/dbc的注释,字节序列表明资源文件的编码是UTF-8-BOM,我是这样解决的:
- 我转到磁盘中的源文件,该文件在我的项目中被视为资源
- 我用Notepad++编辑的
- 编码 -> 转换为 UTF-8
之后,原始帖子中发布的完全相同的代码完美运行。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)