json.net反序列化从项目资源加载json时抛出exception
这是产生问题的反序列化:
public MyType ProblematicDeserialization(jsonString) { return Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString); }
它的工作方式还是没有关于如何加载jsonString的方法:
情况1:
myObjectType
使用json.net作为字符串序列化,然后写入filePath
:
//This line works correctly: dynamic correctlyWorkingJson = IO.File.ReadAllText(filePath, Text.Encoding.UTF8);
案例2
与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; }
在调试器上, notWorkingJson
和notWorkingJson
看起来完全相同,但显然有些东西会使json.net反序列化不接受资源json。
在/ u / dbc注释后,字节序列表明资源文件的编码是UTF-8-BOM,我这样解决了:
- 我去了磁盘中的源文件,该文件在我的项目中被视为资源
- 我用Notepad ++编辑了它
- 编码 – >转换为UTF-8
在那之后,在原帖中发布的完全相同的代码工作得很好。
首先你的样本不编译,我猜你的意思
public MyType ProblematicDeserialization(s) { return Newtonsoft.Json.JsonConvert.DeserializeObject