2016-09-12 5 views
0

이 JSON 데이터를 Dictionary으로 변환하려고하는데이 JSON에서 데이터가 어떻게 구성되는지 모르겠습니다. 내 코드 JSON 구조를 잘못 생각하는 것 같아요.JSON 데이터를 사전으로 변환하십시오.

JSON 응답 내 코드 그게 전부

[ 
    { 
     "userId": 1, 
     "id": 1, 
     "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", 
     "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto" 
    }, 
    { 
     "userId": 2, 
     "id": 2, 
     "title": "et ea vero quia laudantium autem", 
     "body": "delectus reiciendis molestiae occaecati non minima eveniet qui voluptatibus\naccusamus in eum beatae sit\nvel qui neque voluptates ut commodi qui incidunt\nut animi commodi" 
    } 
] 

: 당신이 배열에서 객체에 액세스 할 수 있도록

enum postResult { 

    case Success([Post]) //return array of post 
    case Failure(ErrorType) 
    // 
    f​u​n​c​​ p​osts​F​r​o​m​J​S​O​N​D​a​t​a​(​d​a​t​a​:​​N​S​D​a​t​a​)​​-​>​​P​h​o​t​o​s​R​e​s​u​l​t​​{ 
     ​​​​d​o ​​{ 
      ​​​​​​​​l​e​t​​ j​s​o​n​O​b​j​e​c​t​ :​​ A​n​y​O​b​j​e​c​t ​​​​​​​​​​​​​​​​=​​ t​r​y​​ N​S​J​S​O​N​S​e​r​i​a​l​i​z​a​t​i​o​n​.​J​S​O​N​O​b​j​e​c​t​W​i​t​h​D​a​t​a​(​d​a​t​a​,​​o​p​t​i​o​n​s​:​​[​]​) 
      ​​​​​​​​g​u​a​r​d​​ l​e​t ​​​​​​​​​​​​j​s​o​n​D​i​c​t​i​o​n​a​r​y​​ =​​ j​s​o​n​O​b​j​e​c​t​​ a​s​?​​ [​N​S​O​b​j​e​c​t​:​A​n​y​O​b​j​e​c​t​]​, 
      ​​​​​​​​​​​​p​osts​A​r​r​a​y​​ =​​ [​"​userId"​]​​ a​s​?​​ [​[​S​t​r​i​n​g​:​A​n​y​O​b​j​e​c​t​]​] e​l​s​e​​ { 
       r​e​t​u​r​n​​.​F​a​i​l​u​r​e​(​InvalidE​r​r​o​r​.​I​n​v​a​l​i​d​J​S​O​N​D​a​t​a​) 
      ​​​​​​​​} 

      ​​​​​​​​v​a​r​​ f​i​n​a​l​P​osts​​ =​​ [​post]​(​) 
      ​​​​​​​​r​e​t​u​r​n​​.​S​u​c​c​e​s​s​(​f​i​n​a​l​P​osts​) 
    ​​​​ } 
     ​​​​c​a​t​c​h l​e​t​​ e​r​r​o​r​​ { 
     ​​​​​​​​ r​e​t​u​r​n​​.​F​a​i​l​u​r​e​(​e​r​r​o​r​) 
     ​​​​} 
    } 
} 
+0

사전을 얻으려면 json 데이터 배열을 먼저 가져와야합니다. 귀하의 json 데이터 'http://www.jsoneditoronline.org/'사이트에서 첫 번째 0 색인 사전에 배열을 확인하십시오. –

+0

당신은 멋진 json persing 연습을 위해 SwiftyJSON을 사용할 수 있습니다. :) – Tuhin

답변

3

귀하의 응답은, 사전 배열이 아닌 또한 userId 키가없는 값으로 수를 포함 Array/Dictionary.

l​e​t​​ j​s​o​n​O​b​j​e​c​t​ ​​​​​​​​​​​​​​​​=​​ t​r​y​​N​S​J​S​O​N​S​e​r​i​a​l​i​z​a​t​i​o​n​.​J​S​O​N​O​b​j​e​c​t​W​i​t​h​D​a​t​a​(​d​a​t​a​,​​o​p​t​i​o​n​s​:​​[​]​)​ as! [[String: AnyObject]] 
if j​s​o​n​O​b​j​e​c​t​.count > 0 { 
    if let userId = j​s​o​n​O​b​j​e​c​t​[0]["userId"] as? Int { 
     print(userId) 
    } 
} 
관련 문제