【问题标题】:Json to C# not de-serializing currency symbol correctlyJson 到 C# 没有正确反序列化货币符号
【发布时间】:2019-04-11 11:45:33
【问题描述】:

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

我可以向AddJsonOptions 添加一个设置以确保该符号不会被更改吗?

JSON "SomeProperty": "英镑 £",

C# 属性 SomeProperty="磅�"

【问题讨论】:

  • 如果你能提供minimal reproducible example就太好了
  • 您确实意识到并非所有字体都有£ 字符。而且,如果您输出的字符在字体中没有映射,它通常会呈现为 U+FFFD(又名替换字符)并显示为
  • 同意我们需要minimal reproducible example 来帮助您。您确定文件appsetting.json 编码正确吗? Json.NET 肯定支持有效的 Unicode 字符,所以问题很可能出在StreamReader 级别。
  • 即使文件编码存在一些您无法追踪的问题,您也可以随时在 JSON 中将 £ 转义为 "\u00A3",例如{"currency_sign" : "\u00A3"}。有关示例,请参见 dotnetfiddle.net/4ViVcv

标签: c# json serialization asp.net-core-webapi asp.net-core-2.0


【解决方案1】:

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

我通过在记事本中打开文件并使用 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);
}

【讨论】:

    【解决方案2】:

    我也有这个问题。我做了如下

    \u00A3 
    

    是英镑符号 (£)。我使用下面的代码使用它

    if (yourJsonString.Contains("£"))
    {
         yourJsonString = yourJsonString.Replace("£", "\\u00A3");
    }
    

    这对我有用。

    【讨论】:

      猜你喜欢
      • 2012-01-29
      • 2019-08-21
      • 1970-01-01
      • 2019-04-06
      • 1970-01-01
      • 1970-01-01
      • 2010-11-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多