【问题标题】:Serializing UTF-8序列化 UTF-8
【发布时间】:2014-12-23 13:54:33
【问题描述】:

我对 .NET 有点新……我已经搜索了大约 4 个小时(可能不够勤奋),我会继续问:

我有以下代码(我正在使用 Newtonsoft JSON.NET),它可以很好地响应我的其他 API(在 JSON 中)。然而问题是,在我的模型中,我传递了包含国际化字符的参数,例如以下 'Ç' :这些字符很好地从模型中出来(或者至少,我认为),但它们被正确传递。但是,当它们被序列化到输出中时,它们会像这样(例如)出现乱码:

'Ç' =>
A|™©

this.serializer.Serialize(context.HttpContext.Response.Output, this.Model);

我做错了什么?

【问题讨论】:

  • 声明的输出编码是什么?如果它显示多个字符而不是一个国际字符,那么您似乎必须声明您的输出不是纯 ASCII。
  • @YurySchkatula public override void ExecuteResult(ControllerContext context) { if (context == null) throw new ArgumentNullException("context"); context.HttpContext.Response.ContentType = "application/json"; context.HttpContext.Response.Charset = "UTF-8"; this.serializer.Serialize(context.HttpContext.Response.Output, this.Model); } 抱歉,我不确定如何格式化,但这就是我目前所拥有的
  • 那你的浏览器端编码是什么?
  • 我正在使用 Unicode,并且我确定序列化程序正在正确生成字符串/对象,但由于某种原因,响应流没有将其正确发送到其他 API……或者可能是其他 API 没有在正确的概念下接收它?
  • 似乎 API 忽略了这个概念,因为非 ASCII 字符在 UTF-8 中由几个字节编码。

标签: c# .net json json.net


【解决方案1】:

在进一步探索这个问题后,我发现以下是一个有用的答案,可以解决问题。

Setting the charset of html response content to 1252

2015 年 1 月 2 日更新

public override void ExecuteResult(ControllerContext context)
{
if (context == null) throw new ArgumentNullException("context");
context.HttpContext.Response.ContentType = "application/json";
context.HttpContext.Response.ContentEncoding = System.Text.Encoding.UTF8;
this.serializer.Serialize(context.HttpContext.Response.Output, this.Model);
}

我必须将两边(两个 API)的编码设置为 UTF8

【讨论】:

    猜你喜欢
    • 2012-07-03
    • 1970-01-01
    • 2016-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-10
    • 2019-07-20
    • 2012-09-22
    相关资源
    最近更新 更多