【问题标题】:Export json from python to C# file encoding issue将 json 从 python 导出到 C# 文件编码问题
【发布时间】:2015-08-27 14:21:40
【问题描述】:

我有一个 python 脚本,它生成一个 json 文件,该文件进一步用于 C# 应用程序。这是创建导出的代码:

def put(data, filename):
    with open(filename, 'w') as outfile:
        json.dump(data, outfile, indent=4, ensure_ascii=False, encoding='utf8')

然后在 C# 应用程序中,我尝试通过以下方式读取它:

public static string readFile(string filename)
{
    using (StreamReader r = new StreamReader(filename))
    {
        return r.ReadToEnd();
    }
}

//different file
string json_result = funcs.readFile(out_file);
VirtualMachine newvm = JsonConvert.DeserializeObject<MyClass>(json_result);

问题是 json_result 在每个换行符处包含字符 \r\n 并且无法反序列化 json。

我试图检查python脚本产生的编码,根据SublimeText是u'Undefined'

如何让 python 为 C# 正确编码文件或让 C# 以正确的编码加载它?

【问题讨论】:

    标签: c# python json readfile file-encodings


    【解决方案1】:

    我想正在发生的事情是您在 Windows 系统上,python 脚本的 open 命令会自动使换行符以 \r\n 结尾,而 C# 读者并不期望它们。

    解决此问题的一种方法是将文件作为二进制而不是文本写入文件:

    def put(data, filename):
        with open(filename, 'wb') as outfile:
            outfile.write(json.dumps(data, indent=4, ensure_ascii=False).encode("utf-8"))
    

    但是,在使用 indent 时,问题也可能在 JSON 库本身内部,这可以通过删除参数(但我假设您希望它漂亮是有原因的)或编辑 JSON 字符串来解决生成它并在写入文件之前用/n 替换/r/n

    【讨论】:

      猜你喜欢
      • 2021-05-23
      • 2016-07-13
      • 2016-11-27
      • 1970-01-01
      • 2019-08-10
      • 2014-06-19
      • 1970-01-01
      • 2018-06-30
      • 2017-01-22
      相关资源
      最近更新 更多