2012-01-09 8 views
5

u1234 \のようにエスケープは、私は次のようにJSON形式の結果を返すメソッドを実装しています

{"success":true,"data":[{"Title":"Here could be characters like \u00e5\u00e4\u00f6","Link":"http:\/\/www.url.com\/test",...}, 

どうすればいいですか? web.configでそれを変換、解析、またはresponseEncodingを変更して、Unicode文字を表示させることはできますか?

+3

あなたはUTF-8ではなく '\ u'エスケープを書いていますか? UTF-8はUnicodeの有効なエンコーディングであり、ブラウザはそれをうまく理解します。なぜあなたは '\ u'エスケープが必要ですか? – Rup

+0

私たちのiPhoneアプリを開発している第3の会社は、この形式でそれを持っている必要があると言います。なぜかわからないけど、Xコードとチタニウムとは何か関係があった。 – Maxelsson

答えて

4

サーバーがコンテンツの種類とコンテンツのエンコーディングについてクライアントに正しく伝えていれば、クライアントがWebブラウザまたはhttpを正しく処理する他のクライアントであれば、エスケープする必要はありません。送信データのコードポイント。

クライアントが正しく動作せず、本当にそのような文字列をエスケープする必要がある場合は、独自のActionResultクラスを作成して自分自身でエスケープする必要があります。 JsonResultから継承してから、reflectionを使用してJSON文書を好きなように作成します。

これは雑用です! System.Web.Script.Serialization.JavaScriptSerializer jsonSerializer =新しいのSystem.Webを:

EDIT:このことができますが、私はラインの下に使用してUnicode文字を取得した場合、これはあなたが

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"); 
    } 
} 
+0

クライアントは、別の会社によってTitaniumで開発されたiphoneアプリです。実際の文字列と特殊文字のエスケープ方法はC#のように見えますか?置換は機能しませんか? – Maxelsson

+0

いいえ、リフレクターなどを使ってHtmlEncodeやAntiXssライブラリを見ると、一度に1文字ずつ入力構造体をスキャンしてからStringBuilderに出力されることがわかります。 – Rup

+0

あなたが正しい方向に着手できるように自分の答えを更新しました。 –

0

エスケープする方法はいくつかありますが、どれもあなたが望むものと正確に一致しません。(HtmlEncode and UrlEncode)エスケープするにはユーザー定義関数が必要です。

0

わからない始めます.Script.Serialization.JavaScriptSerializer(); return Json(jsonSerializer.Serialize(validationResult));

関連する問題