How do I decode JSON(JSON Web Token) in Swift 4?

How do I decode this json in Swift 4, with decoder? I want to be able to get the "token" by itself, so I can store it in the Keychain.

{
  "success":true,
  "token":"***"
      ,
  "user": {
    "id": "59f0ec6d5479390345980cc8",
    "username": "john",
    "email": "[email protected]"
  }
}

I have tried this, but it doesn't print anything.

let session = URLSession.shared
        let task = session.dataTask(with: request) { (data, _, _) in
            guard let data = data else { return }
            do {
                let jsonwt = try JSONDecoder().decode(JWT.self, from: data)
                print(jsonwt.token)
            } catch {}
        }
        task.resume()
    }

I can put this after the catch, but that gets the whole json, and I don't want that.

print(String(data: data, encoding: .utf8)!)

Here are the structures. I think this is where the problem lies.

struct User: Decodable {
    let id: String
    let username: String
    let email: String
}

struct JWT: Decodable {
    let success: String
    let token: String
    let user: User
}

Upvotes: 0

Views: 3271

Answers (2)

mica
mica

Reputation: 4308

Works like this:

struct User : Codable
{ var id : String
}

struct JWT : Codable
{ var success : Bool
  var token : String
  var user :User
}


let json = """
{   \"success\" : true,
    \"token\" : \"***\",
    \"user\":
    {   \"id\": \"59f0ec6d5479390345980cc8\",
        \"username\": \"john\",
        \"email\": \"[email protected]\"
    }
}
"""

let decoder = JSONDecoder()
let jwt = try decoder.decode(JWT.self, from: json.data(using: .utf8)!)
print ("token: \(jwt.token)")

Upvotes: 2

David S.
David S.

Reputation: 6705

Here's some playground code that demonstrates the code for parsing JSON in Swift:

//: Playground - noun: a place where people can play

import UIKit
import XCTest
import PlaygroundSupport

let json = """
{
"success":true,
"token":"***"
,
"user": {
"id": "59f0ec6d5479390345980cc8",
"username": "john",
"email": "[email protected]"
}
}
""".data(using: .utf8)!

do {
    if let data = try JSONSerialization.jsonObject(with: json, options: .allowFragments) as? [String:Any], let token = data["token"] {
        print("token is \(token)")
    }
} catch _ {
    print("Failed to decode JSON")
}

Upvotes: 2

Related Questions