Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/107.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 从json文件获取特定值_Ios_Json_Swift_Instagram Api - Fatal编程技术网

Ios 从json文件获取特定值

Ios 从json文件获取特定值,ios,json,swift,instagram-api,Ios,Json,Swift,Instagram Api,我正在尝试使用instagram的API获取instagram用户名,以下是我的代码: private func getUserInfo() { let request = NSMutableURLRequest(url: NSURL(string: "https://api.instagram.com/v1/users/self/?access_token=\(Settings.Access_Token)")! as URL, cachePolicy: .useProtocolCac

我正在尝试使用instagram的API获取instagram用户名,以下是我的代码:

private func getUserInfo() {

    let request = NSMutableURLRequest(url: NSURL(string: "https://api.instagram.com/v1/users/self/?access_token=\(Settings.Access_Token)")! as URL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)

    let session = URLSession.shared
    let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
        guard let data = data else { return }
        print(String(data: data, encoding: .utf8)!)
    })
    dataTask.resume()
}
print语句返回以下内容以便正常工作,但我不知道如何访问和存储username值,我不理解其他人对类似主题的响应:

{
  "data": {
    "id": "253876051",
    "username": "bruncheveuxcourtsyeuxverts",
    "profile_picture": "https:\/\/scontent.cdninstagram.com\/vp\/7eb0427fdd53a5b319d04c22af1c9f63\/5C977089\/t51.2885-19\/s150x150\/46724860_307687986508947_185550859294212096_n.jpg?_nc_ht=scontent.cdninstagram.com",
    "full_name": "Lo\u00efc Buckwell",
    "bio": "Gogole de p\u00e8re en fils",
    "website": "",
    "is_business": false,
    "counts": {
      "media": 16,
      "follows": 106,
      "followed_by": 406
    }
  },
  "meta": {
    "code": 200
  }
}

可以使用jsonSerialization将json对象转换为swift dictionary对象

For example

let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let dataResponse = data,
          error == nil else {
          print(error?.localizedDescription ?? "Response Error")
          return }  
    do{ 
        //here dataResponse received from a network request 
        let jsonResponse = try JSONSerialization.jsonObject(with:
                               dataResponse, options: []) 
        print(jsonResponse) //Response result 
     } catch let parsingError {
        print("Error", parsingError) 
   }
}
task.resume()

另一种选择是在Swift中使用可编码系统:

struct Counts: Codable {
    enum CodingKeys: String, CodingKey {
        case followedBy = "followed_by"
        case follows
        case media
    }
    let followedBy: Int
    let follows: Int
    let media: Int
}

struct InstagramUser: Codable {
    enum CodingKeys: String, CodingKey {
        case bio
        case counts
        case fullName = "full_name"
        case id
        case isBusiness = "is_business"
        case profilePicture = "profile_picture"
        case username
        case website
    }

    let bio: String
    let counts: Counts
    let fullName: String
    let id: String
    let isBusiness: Bool
    let profilePicture: String
    let username: String
    let website: String
}

struct Meta: Codable {
    let code: Int
}

struct Output: Codable {
    enum CodingKeys: String, CodingKey {
        case user = "data"
        case meta
    }
    let user: InstagramUser
    let meta: Meta
}
现在,在您的区块内,您可以使用:

let ouptut = try! JSONDecoder().decode(Output.self, from: data)
let fullName = output.user.fullName

好的,谢谢!这对我帮助很大,但是我如何存储“username”值作为示例?让username=jsonResponse[“data”][“username”]
let username=((foo-as![String:Any])[“data”]as![String:Any])[“full_-name”]相当难看。一个更好的选择是使用像SwiftyJSON这样的解析库。尝试了这个@lineshkmohan,但我得到一个错误“Type'Any'没有下标成员”尝试Daniel的注释。让userName=((jsonResponse as![String:Any])[“data”]as![String:Any])[“userName”]as!StringYou可能需要将
数据
更改为另一个名称,以避免与基金会中的
数据
结构发生冲突。能否使用Codable仅提取全名?我更喜欢第一个解决方案,因为我不太理解此解决方案,但无论如何,谢谢@不要把时间浪费在其他人身上solution@LeoDabus哪种解决方案更好?