0

我有一个 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# 以正确的编码加载它?

4

1 回答 1

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"))

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

于 2015-08-27T14:31:19.597 回答