当从项目资源加载json时,json.net反序列化抛出异常



这是产生问题的反序列化:

public MyType ProblematicDeserialization(jsonString)
{
    return Newtonsoft.Json.JsonConvert.DeserializeObject<MyType>(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;
}

在调试器上,correctlyWorkingJsonnotWorkingJson看起来完全相同,但显然有一些东西使资源json不被json.net反序列化接受。

在/u/dbc注释字节序列表明资源文件的编码是UTF-8-BOM之后,我以这种方式解决了它:

  • 我去到磁盘上的源文件,它在我的项目中被视为资源
  • 我用notepad++编辑
  • Encoding -> Convert to UTF-8

之后,在原始帖子中发布的完全相同的代码工作得很好。

首先您的示例没有编译,我假设您的意思是

public MyType ProblematicDeserialization(s)
{
    return Newtonsoft.Json.JsonConvert.DeserializeObject<MyType)(s);   
}

最新更新