2016-09-16 6 views
-1

public 클래스의 일부 dataTables 플러그인의 데이터 구조를 빌드했습니다.C# 문자열을 JSON으로 변환

데이터 구조를 구축하는 코드는 다음과 같습니다이 잘 실행 예상대로 테이블을 생성

 var response = "{ \"data\": ["; 
      response = response + "["; 
      response = response + "\"Clark, Keith\","; 
      response = response + "\"Corporate\","; 
      response = response + "\"XXX-XXX-XXXX\","; 
      response = response + "\"XXX-XXX-XXXX\","; 
      response = response + "\"[email protected]\""; 
      response = response + "],"; 
      response = response + "["; 
      response = response + "\"Clark, Keith\","; 
      response = response + "\"Corporate\","; 
      response = response + "\"YYY-YYY-YYYY\","; 
      response = response + "\"YYY-YYY-YYYY\","; 
      response = response + "\"[email protected]\""; 
      response = response + "]"; 
     response = response + "] }"; 

     return response; 

. 문제가있는 곳은 HTML 마크 업을 필드에 추가하려고 할 때입니다. 나는이 같은 상태를 나타 내기 위해 이름 옆에있는 글꼴 멋진 아이콘을 사용하려면 : 내가 읽고 내 코드를 수정 시도

<i class="fa fa-arrow-up" style="color: #00ff00;" aria-hidden="true"> 

:

response = response + "\"<i class=\"\"fa fa-arrow-up\"\" style=\"\"color: #00ff00;\"\" aria-hidden=\"\"true\"\">Clark, Keith\","; 

을하지만 지금은 오류를 수신하고 그 JSON의 형식이 올바르지 않습니다. 무언가가 누락되었거나 JSON 구조 안에 HTML 마크 업을 사용할 수 있습니까?

+0

아무 것도 놓치지 않았습니다. html 마크 업은 유효한 JSON이 아닙니다. JSON 문자열은 완전히 자체 포함되어야합니다. –

+0

그 새 물건을 넣은 json을 게시하십시오. 마지막 닫기 후에 추가하려고하지 않습니까? – Dispersia

+0

@JonathonChase 거기에 html이있는 것은 아무 문제가 없습니다. html은 JSON이 정확히 무엇인지 정확하게 나타내는 정적 텍스트입니다. – Dispersia

답변

0

문제는 잘못된 json 문자열 리터럴을 생성하고 있다는 것입니다.

"<i class=""fa fa-arrow-up"" style=""color: #00ff00;"" aria-hidden=""true"">Clark, Keith", 

따옴표는 리터럴 백 슬래시를 사용하여 이중화하지 않고 이스케이프 처리됩니다.

대신이 작업을 수행했을 것이다 : 정확히 같은 문자열을 생성하지 않아야하는 이유

"\"<i class=\\\"fa fa-arrow-up\\\" style=\\\"color: #00ff00;\\\" aria-hidden=\\\"true\\\">Clark, Keith\"," 

이 보여줍니다. 거기에는 당신을 위해 이것을 안전하게 할 수있는 툴이 있습니다. Json.net은이 작업을 쉽게 처리 할 것입니다. 그와

var markup = "<i class=\"fa fa-arrow-up\" style=\"color: #00ff00;\" aria-hidden=\"true\">"; 
var response = new JObject 
{ 
    ["data"] = new JArray 
    { 
     new JArray 
     { 
      markup + "Clark, Keith", 
      "Corporate", 
      "XXX-XXX-XXXX", 
      "XXX-XXX-XXXX", 
      "[email protected]", 
     }, 
     new JArray 
     { 
      markup + "Clark, Keith", 
      "Corporate", 
      "YYY-YYY-YYYY", 
      "YYY-YYY-YYYY", 
      "[email protected]", 
     }, 
    } 
}; 
return response.ToString(); 

는 데이터에 마크 업을 추가하지 않아야 말했다. 데이터는 데이터이며 그 이상은 아닙니다. 표시 방법에 영향을 주려면 해당 마크 업을보기에 추가해야합니다.