[英]how to convert JSON-String into Array of Dictionaries in iOS Swift 3
[英]How to convert escaped JSON-string to NSString?
我正在使用一個http服務器,它在響應正文中返回JSON字符串:
"Some text.\nSome text.\n\t\"Some text in quotes.\""
我需要在字符串的開頭和結尾刪除引號,我需要unescape特殊符號。 我為NSString制作類別,但我認為這是錯誤的實現: https : //gist.github.com/virasio/59907e087f859e6c1723我有其他想法。 我可以使用NSJSONSerialization:
NSString *sourceString = @"\"Some text.\\nSome text.\\n\\t\\\"Some text in quotes.\\\"\"";
NSString *jsonObject = [NSString stringWithFormat:@"{ \"value\" : %@ }", sourceString];
NSDictionary *object = [NSJSONSerialization JSONObjectWithData:[jsonObject dataUsingEncoding:NSUTF8StringEncoding options:0 error:NULL]];
NSString *result = [object objectForKey:@"value"];
但是......它也不好。
默認情況下,Foundation將僅解析JSON對象或數組,但如果您告訴它接受JSON片段,它可以解析字符串,數字和布爾值:
NSData *data = [@"\"Some text.\\nSome text.\\n\\t\\\"Some text in quotes.\\\"\""
dataUsingEncoding:NSUTF8StringEncoding];
id result = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:NULL];
NSLog(@"[result class] = %@", [result class]);
NSLog(@"result = %@", result);
產量:
[result class] = __NSCFString result = Some text. Some text. "Some text in quotes."
這實際上是傳遞error
確實有幫助的情況之一。 我試過沒有傳遞NSJSONReadingAllowFragments
並得到一個非常明確的錯誤消息:
錯誤域= NSCocoaErrorDomain代碼= 3840“操作無法完成。(Cocoa錯誤3840。)”( JSON文本沒有以數組或對象開頭,並且選項允許未設置片段。 )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.