我正在实现一个返回 json 结果的方法,例如:
public JsonResult MethodName(Guid key){
var result = ApiHelper.GetData(key); //Data is stored in db as varchar with åäö
return Json(new { success = true, data = result },"application/json", Encoding.Unicode, JsonRequestBehavior.AllowGet );
}
显示结果:
{"success":true,"data":[{"Title":"Here could be characters like åäö","Link":"http://www.url.com/test",...},
但我想将其显示为:
{"success":true,"data":[{"Title":"Here could be characters like \u00e5\u00e4\u00f6","Link":"http:\/\/www.url.com\/test",...},
我怎样才能做到这一点?
我可以转换它、解析它或更改 web.config 中的responseEncoding 以使其显示 unicode 字符吗?
如果客户端是Web浏览器或任何其他正确处理http的客户端,则不需要转义,只要您的服务器正确地告诉客户端有关内容类型和内容编码的信息,并且您选择的编码支持传出中的代码点数据。
如果客户端行为不正确,并且确实需要像这样转义字符串,则您必须编写自己的ActionResult
上课并自己逃跑。继承自JsonResult
首先,使用反射来创建您喜欢的 JSON 文档。
这是一件苦差事!
编辑:这将帮助您开始
public class MyController : Controller {
public JsonResult MethodName(Guid key){
var result = ApiHelper.GetData(key);
return new EscapedJsonResult(result);
}
}
public class EscapedJsonResult<T> : JsonResult {
public EscapedJsonResult(T data) {
this.Data = data;
this.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
}
public override ExecuteResult(ControllerContext context) {
var response = context.HttpContext.Response;
response.ContentType = "application/json";
response.ContentEncoding = Encoding.UTF8;
var output = new StreamWriter(response.OutputStream);
// TODO: Do some reflection magic to go through all properties
// of the this.Data property and write JSON to the output stream
// using the StreamWriter
// You need to handle arrays, objects, possibly dictionaries, numbers,
// booleans, dates and strings, and possibly some other stuff... All
// by your self!
}
// Finds non-ascii and double quotes
private static Regex nonAsciiCodepoints =
new Regex(@"[""]|[^\x20-\x7f]");
// Call this for encoding string values
private static string encodeStringValue(string value) {
return nonAsciiCodepoints.Replace(value, encodeSingleChar);
}
// Encodes a single character - gets called by Regex.Replace
private static string encodeSingleChar(Match match) {
return "\\u" + char.ConvertToUtf32(match.Value, 0).ToString("x4");
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)