首页 > 解决方案 > Json 到 C# 没有正确反序列化货币符号

问题描述

我将 C# WebApi 与 .NET Core 2.1 一起使用。我在 appsetting.json 文件中有一个 JSON 属性,当它反序列化为 c# 时,通过AddOptions,£ 符号更改为 �</p>

我可以添加一个设置来AddJsonOptions确保这个符号不会被改变吗?

JSON "SomeProperty": "英镑 £",

C# 属性 SomeProperty="pound �";

标签: c#jsonserializationasp.net-core-webapiasp.net-core-2.0

解决方案


(解决方案从问题迁移到答案):

我通过在记事本中打开文件并使用 UTF-8 编码保存它来解决这个问题。在 VS 中保存文件时,它保留了 UTF-8 编码。不确定 Visual Studio 在创建 appsetting 文件时在做什么,但过去似乎一直是个问题。https://github.com/aspnet/Configuration/issues/241作为记录,我在 Windows 10 上使用 VS2017 15.8.4

应用设置

{
  "SftpConfigList": {
    "SftpConfigs": [
      {
        "Host": "somehost1",
        "Username": "foo",
        "Password": "okokokok"
      },
      {
        "Host": "somehost2",
        "Username": "bar",
        "Password": "pass£££word"
      }
    ]
  }
}


namespace WebApplication1
{
    public class SftpConfigListDto
    {
        public SftpConfigDto[] SftpConfigs { get; set; }
    }

    public class SftpConfigDto
    {
        public string Host { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }
    }
}

启动

public void ConfigureServices(IServiceCollection services)
{
    services.AddOptions();
    services.Configure<SftpConfigListDto>(Configuration.GetSection("SftpConfigList"));
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

推荐阅读