json.net deserialization throwing exception when j

2020-05-04 16:02发布

This is the deserialization that produces the problem:

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

It works or it doesn't deppending on how jsonString is loaded:

CASE 1:

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

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;
}

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.

标签: c# json.net
2条回答
够拽才男人
2楼-- · 2020-05-04 16:23

First you sample does not compile, I assume you mean

public MyType ProblematicDeserialization(s)
{
    return Newtonsoft.Json.JsonConvert.DeserializeObject<MyType)(s);   
}
查看更多
来,给爷笑一个
3楼-- · 2020-05-04 16:26

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:

  • I went to the source file in disk that was treated as a resource in my project
  • I edited it with Notepad++
  • Encoding -> Convert to UTF-8

After that, the exact same code posted in the original post worked perfectly.

查看更多
登录 后发表回答