2016-07-28 83 views
1

我从机器人编程来斯威夫特的iOS编程,并有一个很难解析JSON 这里的字符串我尝试解析:解析JSON与斯威夫特

{"response":[{"uid":111,"first_name":"someName","last_name":"someLastName","photo_100":"http:someUrl/face.jpg"}]} 

这里我如何尝试解析此:

if let dict = Utils.convertStringToDictionary(response)! as? [String: AnyObject]{ 
     // this part is yet doing ok 
     if let response = dict["response"] as? [String: AnyObject]{ 
      NSLog("let response \(response)") 
      if let first_name = response["first_name"] as? String { 
       NSLog("first_name = \(first_name)") 
      } 
     } 
     else { 
      NSLog("not an []") 
     } 

Log消息给我“不是[]”,因为它不能产生响应对象。据我了解,我在做正确的[String: AnyObject]是什么,是我的JSON的“响应”身体

以防万一,这里是我的Utils.convertStringToDictionary方法:这里

public static func convertStringToDictionary(text: String) -> [String:AnyObject]? { 
    if let data = text.dataUsingEncoding(NSUTF8StringEncoding) { 
     do { 
      let json = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) as? [String:AnyObject] 
      return json 
     } catch { 
      NSLog("Something went wrong") 
     } 
    } 
    return nil 
} 
+1

你的“响应”参数数组不字典 –

回答

3
Array in swift denotes with [] 
Dictionary in swift denotes with [:] 
your response parameter is array of dictionary ... so it denotes with [[:]] 

所以只是[[String: AnyObject]]

解析它
if let response = dict["response"] as? [[String: AnyObject]]{ 
    for user in response{ 
     NSLog("let response \(user)") 
     if let first_name = user["first_name"] as? String { 
       NSLog("first_name = \(first_name)") 
      } 
    } 
} 
+0

您能否给我一个关于[[String:AnyObject]]中这个双方括号的解释? – user2976267

+0

非常感谢!所以,响应实际上是一系列字典,对吗? – user2976267

+0

是的...在这[[](http://stackoverflow.com/a/33123953/4601170)..我没有解释括号,在JSON中的括号表明什么...它可能对你有帮助 –

2

问题是响应是一种array

if let response = dict["response"] as? NSArray{ 
    for value in response as? NSDictionary{ 
     print(value["uid"]) /// prints 111 
     print(value["first_name"]) /// prints someName 
    } 
} 
+0

你能告诉我如何解析它呢?我有点困惑,因为它实际上是Java中的HashMap ,但这里是一个数组 - 我如何获得Key的值? – user2976267

+0

我已经添加了我的答案,并添加了经过解析的示例 –

0

试试这个代码

if let dict = Utils.convertStringToDictionary(response)! as? [String: AnyObject]{ 
     // this part is yet doing ok 
     if let response = dict["response"] as? NSArray{ 
     NSLog("let response \(response)") 

     for dict in response{ 

      if let first_name = dict["first_name"] as? String { 
       NSLog("first_name = \(first_name)") 
      } 
     }      

     } 
     else{ 
      NSLog("not an []") 
    } 
}