2017-11-08 2 views
-1

공백과 새 줄을 사용하지 않고 사전을 json 문자열로 변환하려고합니다. JSONSerialization.jsonObject를 사용하려고했지만 여전히 공백과 새 줄을 볼 수 있습니다. 문자열 결과를 가지고 할 수있는 방법이공백과 새 줄을 사용하지 않고 사전을 json 문자열로 변환하는 방법

"data": "{\"requests\":[{\"image\":{\"source\":{\"imageUri\":\"https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png\"}},\"features\":[{\"type\":\"LOGO_DETECTION\",\"maxResults\":1}]}]}" 

내 변환과 같은

var features = [[String: String]]() 
for detection in detections { 
    features.append(["type": imageDetection[detection]!]) 
} 
let content = ["content": base64Image] 
let request = ["image": content, "features": features] as [String : Any] 
let requests = ["requests": [request]] 

let jsonData = try! JSONSerialization.data(withJSONObject: requests, options: .prettyPrinted) 
let decoded = try! JSONSerialization.jsonObject(with: jsonData, options: []) 
print(decoded) 

결과

{ 
    requests =  (
       { 
      features =    (
           { 
        type = "LABEL_DETECTION"; 
       }, 
           { 
        type = "WEB_DETECTION"; 
       }, 
           { 
        type = "TEXT_DETECTION"; 
       } 
      ); 
      image =    { 
       content = "iVBO 
     ........... 
+2

'.prettyPrinted'는 범인입니다 – Callam

+0

옵션을 제거해도 동일한 결과가납니다. –

답변

3

당신은 객체로 직렬화 된 JSON을 디코딩하는이 보인다. 오브젝트가 콘솔에 인쇄되면 들여 쓰기와 등호 기호와 괄호가 사용됩니다.

.prettyPrinted 옵션을 제거하고 데이터를 사용하여 .utf8 인코딩으로 문자열을 초기화하십시오.

let jsonData = try! JSONSerialization.data(withJSONObject: requests, options: []) 
let decoded = String(data: jsonData!, encoding: .utf8)! 
관련 문제