2017-10-05 4 views
-1
{ 
    "3": { 
    "title": "something" 
    }, 
    "28": { 
    "title": "something else" 
    } 
} 

어떻게이 json을 ObjectMapper를 사용하여 Content 객체의 배열로 캐스트 할 수 있습니까?ObjectMapper : 매핑 된 객체의 값으로 사전 키

struct Content: Mappable { 
    var id: String? //Expected value is 3, 28 
    var title: String? //Expected value is "something", "something else" 
} 

미리 감사드립니다. 스위프트 3에서

답변

0

: 먼저 당신이

for i in 0..<keysArray.count { 
    if let key = keysArray[i] as? String { 
     //get your key here 
     if let singleObject = dict[key] as? [String: Any] { 
      if let value = singleObject["title"] as? String { 
       //get you value 
       // get both key & value. Now map it. Hope you get it. 
      } 
     } 
    } 
} 

희망처럼이 사전의 모든 열쇠를 얻을 것이다이 keysArray & 통해이

keysArray = Array(dict.keys) 

이제 루프처럼이 사전의 모든 열쇠를 얻을 도움이됩니다. JSON -

let content = Mapper<Content>().map(JSONString) 

모델 :

let json = Mapper().toJSONString(content, prettyPrint: true) 

을 그리고 당신이 그것을 사용하기 전에 다음을 수행해야합니다 - 모델

JSON :

1

나는 누구 요 이런 식으로 뭔가를 찾고 생각 Content Model을 다음으로 변경하십시오.

struct Content: Mappable { 
    var id: String? //Expected value is 3, 28 
    var title: String? //Expected value is "something", "something else" 

    required init?(_ map: Map) { 

    } 

    // Mappable 
    func mapping(map: Map) { 
     id <- map["id"] 
     title <- map["title"] 
    } 
} 
관련 문제