JSON의 이스케이프 문자 대체
JSON 문자열의 "\" 문자를 빈 공간으로 바꿉니다.내가 어떻게 그럴 수 있을까?
JSON 문자열에서 이스케이프 문자를 모두 삭제하는 가장 쉽고 최선의 방법은 문자열을 Regex에 전달하는 것입니다.Unescape() 메서드.이 메서드는 ecape가 삭제되지 않은 새 문자열을 반환합니다(\n \t 등).
상세한 것에 대하여는, MSDN 의 「Regex」를 참조해 주세요.이스케이프 해제 메서드(String)(시스템).Text.Regular Expressions)
json 객체가 문자열인 경우 에서 설명합니다.net 이스케이프 "\" 문자는 json 문자열인 JObject를 정리할 때 추가됩니다.다음 코드 스니펫에 나타나 있듯이 구문 분석({string})은 정상적으로 정리됩니다.
var myJsonAsString = "{\"Name\": \"John\", \"LastName\": \"Doe\", \"Age\": 199 }";
var myCleanJsonObject = JObject.Parse(myJsonAsString);
이스케이프 문자가 제거된 깨끗한 Json 객체를 제공합니다.
{
"Name": "John",
"LastName": "Doe",
"Age": 199
}
이러한 유형의 이스케이프 문자열은 보통 JSON 문자열을 JSON으로 부호화하려고 할 때 생성됩니다.이것에 의해, 「다양한 레벨의 시리얼화」와 같은 것이 발생합니다.
솔루션:
- 먼저 이스케이프된 문자열을 역직렬화해야 합니다만, 타겟 CLR 타입에는 역직렬화하지 않고, 다른 문자열에 역직렬화해야 합니다.
- 필요에 따라 문자열 유형에 대한 역직렬화를 다시 반복합니다.
- 다음으로 타깃유형에 대한 최종 역직렬화를 수행합니다.
코드:
// Initial example json string: "\"{\\\"Property1\\\":1988,\\\"Property2\\\":\\\"Some data :D\\\"}\""
// First, deserialize to another string (unescaped string).
string unescapedJsonString = JsonConvert.DeserializeObject<string>(escapedJsonString);
// Result: "{\"Property1\":1988,\"Property2\":\"Some data :D\"}"
// Second, deserialize to another string, again (in this case is necessary)
var finalUnescapedJsonString = JsonConvert.DeserializeObject<string>(unescapedJsonString);
// {"Property1":1988,"Property2":"Some data :D"} This time prints a final, unescaped, json string:
// Finally, perform final deserialization to the target type, using the last unescaped string.
MyClass targetObject = JsonConvert.DeserializeObject<MyClass>(finalUnescapedJsonString);
Regex.Unescape()이 방법은 대부분의 경우 정상적으로 동작하지만, 일부의 경우는 커스텀 교환이 필요합니다.예.Regex.Unescape()는 JSON에서 지원되지 않는 실제 줄 바꿈을 생성합니다.
이스케이프되지 않은 JSON:
{"comments_count":27,"comments":"<a name=\"comments\"><\/a>\n\n\t\n\t\n\t\t\n\t<div class=\"CommentsList\">\n\t\t<strong>COMENTARII<\/strong>\n\t\t"}
Regex.탈출 해제
{"comments_count":27,"comments":"<a name="comments"></a>
Replacements
<div class="CommentsList">
<strong>Comments</strong>
"}
커스텀 교환
private string SanitizeReceivedJson(string uglyJson)
{
var sb = new StringBuilder(uglyJson);
sb.Replace("\\\t", "\t");
sb.Replace("\\\n", "\n");
sb.Replace("\\\r", "\r");
return sb.ToString();
}
{"comments_count":27,"comments":"<a name=\"comments\"><\/a>\n\n\t\n\t\n\t\t\n\t<div class=\"CommentsList\">\n\t\t<strong>COMENTARII<\/strong>"}
다른 문자열로 역직렬화한 후 당신의 클래스로 역직렬화합니다.
string resultString = JsonConvert.DeserializeObject<string>(content);
var result = JsonConvert.DeserializeObject<T>(resultString);
이건 나한테 효과가 있었어.
C# 문자열 할당은 이름 또는 값에 \이 포함되어 있으면 이중 이스케이프되지만, 이 작업은 사용자 대신 수행됩니다.적절한 방법은 변수를 사용하는 것입니다.("\\\"",\\"); 또는 변수를 바꿉니다.치환(@"\",@"\");그러면 이중 이스케이프 \ 문자가 삭제되고 REQUIRED \ 값은 그대로 유지됩니다.예를 들어 JSON에 "Domain"이 포함되어 있는 경우사용자 이름" 문자열에 할당하면 "도메인\\사용자 이름\"으로 반환됩니다.\사용자명
c#에서는 표준 JSON 결과를 작성하는 방법은 다음과 같습니다.
사용자 지정 속성 이름으로 클래스를 하나 추가한 다음 Json(myClassForJsonResult)을 아래쪽 코드로 반환해야 합니다.
public ActionResult testJsonData()
{
var myClassForJsonResult=new YourClassOfYourCustomProperties();
myClassForJsonResult.FirstPropertyStringType="first";
myClassForJsonResult.SecondPropertyIntType=2;
return Json(myClassForJsonResult);
}
클래스 정의:
public class YourClassOfYourCustomProperties
{
public string FirstPropertyStringType{ get; set; }
public int SecondPropertyIntType{ get; set; }
}
Regex 를 사용할 수 있습니다.Unescape(yourEscapeString);
var json = 시스템.텍스트, Json.Json Serializer 입니다.역직렬화 <Json Element> (escape Json)
Json 데이터
[{
"Artnr":"HRA1/SIKT"
}]
위의 데이터를 해석하는 동안 잘못된 이스케이프 문자 문제에 직면했습니다.데이터에 대한 다음 방법을 호출하여 수정
string cleanJson = Regex.Unescape(myJsonData);
그런 다음 cleaJson을 사용하여 json을 Clas로 역직렬화합니다.
이거 먹어봐
json.Replace(@"\", " ")
기본적으로 C#의 백슬래시를 교환하는 방법을 묻고 있습니다.
쓰셔야 돼요.String.Replace이 에는 다음과 같은내용이 적혀 있습니다.
String.ReplaceString,
현재 인스턴스에서 지정된 모든 문자열이 지정된 다른 문자열로 대체되는 새 문자열을 반환합니다.
된 값을 합니다.Replace 삭제:
jsonString= jsonString.Replace(@"\"," ");
을 잡고 json으로 해 .String.Replace()
string JsonContentFixed = JsonContentString.Replace(@"\", " ");
string variable = "{\"data\": {\"id\": \"1\",\"name\": \"jon\"}}";
Console.WriteLine(variable.Replace("\\", " "));
언급URL : https://stackoverflow.com/questions/16692371/replacing-escape-characters-from-json
'programing' 카테고리의 다른 글
| Mongoose에서 고유한 값을 쿼리하려면 어떻게 해야 합니까? (0) | 2023.03.06 |
|---|---|
| jQuery.getJSON - 접근컨트롤-허용-발신원 문제 (0) | 2023.03.06 |
| 모서리에서의 더블 버튼 클릭 방지/처리 (0) | 2023.03.06 |
| JsonNode에 새 노드를 만드는 방법 (0) | 2023.03.06 |
| gson이 Malformed Json Exception을 슬로우하다 (0) | 2023.03.06 |