자바 스크립트 사용을 위해 C #의 이스케이프 따옴표
JSON 형식으로 쿼리 결과를 반환하는 ASP.Net 웹 처리기가 있습니다.
public static String dt2JSON(DataTable dt)
{
String s = "{\"rows\":[";
if (dt.Rows.Count > 0)
{
foreach (DataRow dr in dt.Rows)
{
s += "{";
for (int i = 0; i < dr.Table.Columns.Count; i++)
{
s += "\"" + dr.Table.Columns[i].ToString() + "\":\"" + dr[i].ToString() + "\",";
}
s = s.Remove(s.Length - 1, 1);
s += "},";
}
s = s.Remove(s.Length - 1, 1);
}
s += "]}";
return s;
}
문제는 때때로 반환 된 데이터에 따옴표가 있고 js 객체로 제대로 생성 될 수 있도록 javascript-escape가 필요하다는 것입니다. 내 데이터에서 따옴표를 찾고 (인용문이 매번 존재하지 않음) 그 앞에 "/"문자를 배치하는 방법이 필요합니다.
응답 텍스트의 예 (잘못된) :
{"rows":[{"id":"ABC123","length":"5""},
{"id":"DEF456","length":"1.35""},
{"id":"HIJ789","length":"36.25""}]}
"를 이스케이프해야하므로 내 응답은 다음과 같아야합니다.
{"rows":[{"id":"ABC123","length":"5\""},
{"id":"DEF456","length":"1.35\""},
{"id":"HIJ789","length":"36.25\""}]}
또한 저는 C # (일반적으로 코딩)에 익숙하지 않으므로 코드의 다른 내용이 어리석은 것처럼 보이면 알려주십시오.
.net 4.0 +의 경우 표준이 있습니다. HttpUtility.JavaScriptStringEncode
Lone Coder가 설명한 초기 서풍 솔루션의 경우 매우 좋습니다.
다음은 http://www.west-wind.com/weblog/posts/114530.aspx 에서 찾은 효율적이고 강력한 방법입니다 .
/// <summary>
/// Encodes a string to be represented as a string literal. The format
/// is essentially a JSON string.
///
/// The string returned includes outer quotes
/// Example Output: "Hello \"Rick\"!\r\nRock on"
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static string EncodeJsString(string s)
{
StringBuilder sb = new StringBuilder();
sb.Append("\"");
foreach (char c in s)
{
switch (c)
{
case '\"':
sb.Append("\\\"");
break;
case '\\':
sb.Append("\\\\");
break;
case '\b':
sb.Append("\\b");
break;
case '\f':
sb.Append("\\f");
break;
case '\n':
sb.Append("\\n");
break;
case '\r':
sb.Append("\\r");
break;
case '\t':
sb.Append("\\t");
break;
default:
int i = (int)c;
if (i < 32 || i > 127)
{
sb.AppendFormat("\\u{0:X04}", i);
}
else
{
sb.Append(c);
}
break;
}
}
sb.Append("\"");
return sb.ToString();
}
I think you should rather look at the JavaScriptSerializer class. It's a lot more stable, and will correctly handle any kind of data or escape characters etc. Also, your code will look a lot cleaner.
In your case your class can look like this:
public static String dt2JSON(DataTable dt) {
var rows = new List<Object>();
foreach(DataRow row in dt.Rows)
{
var rowData = new Dictionary<string, object>();
foreach(DataColumn col in dt.Columns)
rowData[col.ColumnName] = row[col];
rows.Add(rowData);
}
var js = new JavaScriptSerializer();
return js.Serialize(new { rows = rows });
}
This method will return a correctly serialized json string... For example, sth like this:
{"rows":[{"id":1,"name":"hello"},{"id":2,"name":"bye"}]}
Have fun! :)
To correctly escape a string literal for Javascript, you first escape all backslash characters, then you escape the quotation marks (or apostrophes if you use them as string delimiters).
So, what you need is:
value.Replace("\\","\\\\").Replace("\"","\\\"")
What else jumps out to me is that you are using string concatenation in a loop. This is bad, as it scales very poorly. The += operator does not add characters at the end of the existing string (as strings are immutable and can never be changed), instead it copies the string and the added characters to a new string. As you copy more and more data each time, eEvery additional row roughly doubles the execution time of the method. Use a StringBuilder to build the string instead.
Use the ColumnName
property to get the name of a column rather than the ToString
method. The ToString
method returns the Expression
property value if it's set, only if that is not set does it return the ColumnName
property.
public static String dt2JSON(DataTable dt) {
StringBuilder s = new StringBuilder("{\"rows\":[");
bool firstLine = true;
foreach (DataRow dr in dt.Rows) {
if (firstLine) {
firstLine = false;
} else {
s.Append(',');
}
s.Append('{');
for (int i = 0; i < dr.Table.Columns.Count; i++) {
if (i > 0) {
s.Append(',');
}
string name = dt.Columns[i].ColumnName;
string value = dr[i].ToString();
s.Append('"')
.Append(name.Replace("\\","\\\\").Replace("\"","\\\""))
.Append("\":\"")
.Append(value.Replace("\\","\\\\").Replace("\"","\\\""))
.Append('"');
}
s.Append("}");
}
s.Append("]}");
return s.ToString();
}
string.Replace(<mystring>, @"\"", @"\\"");
Why don't you just do this:
string correctResponseText = wrongResponseText.Replace("\"", "\\\"");
Works when i need send string from C# to html tag.
<buton onlick="alert('<< here >>')" />
HttpUtility.HtmlEncode
Well, for starters you do not need quotes around the keys.
{rows:[,]} is valid.
and you could dt.Table.Columns[i].ToString().Replace("\","")
But if you want to retain the double quotes, single quote works the same way double quotes do in JS
Otherwise you could do
String.Format("{name: \"{0}\"}",Columns[i].ToString().Replace("\",""))
참고URL : https://stackoverflow.com/questions/806944/escape-quote-in-c-sharp-for-javascript-consumption
'Program Tip' 카테고리의 다른 글
자바의 ConcurrentHashMap 및 Hashtable (0) | 2020.12.02 |
---|---|
컬 오류 60, SSL 인증서 문제 : 인증서 체인의 자체 서명 된 인증서 (0) | 2020.12.02 |
Python에서 문자열 찾기의 예 (0) | 2020.12.02 |
개체 목록에 대해 동일한 메서드를 호출하는 방법은 무엇입니까? (0) | 2020.12.02 |
ZooKeeper가 실행 중인지 또는 명령 프롬프트에서 실행 중인지 확인하는 방법은 무엇입니까? (0) | 2020.12.02 |