gpt4 book ai didi

c# - 如何使用转义为\u1234 的 unicode 字符返回 json 结果

转载 作者:太空狗 更新时间:2023-10-29 23:25:35 26 4
gpt4 key购买 nike

我正在实现一个返回 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 字符吗?

最佳答案

如果客户端是网络浏览器,或者任何其他正确处理 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");
}
}

关于c# - 如何使用转义为\u1234 的 unicode 字符返回 json 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8785912/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com