0

I'm trying to get data drom the json array, this is the code that i'm trying, the thing is that i would like to get only the name that is inside this json

    {
"tag": "getuser",
"success": 1,
"error": 0,
"uid": "56108b7e651ad2.95653404",
"user": {
    "name": "2",
    "phone": "2",
    "email": "2"
        }
   }

I tryied this

                let jsonData:NSDictionary = try NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers ) as! NSDictionary

                let  name = jsonData["user"]
                print("Nombre del usuarioes: \(name)")

But this prints the whole user data, name, phone and email, how can i be able to print only the name or only the email?

0

3 Answers 3

2

You don't have to use a library and you don't have to use key-value coding.

The same way you're already using subscripting for your dictionary with this:

let name = jsonData["user"]

you just have to continue subscripting to find your value.

Example:

do {
    let jsonData = try NSJSONSerialization.JSONObjectWithData(urlData!, options: []) as! NSDictionary
    let user = jsonData["user"]!
    let name = user["name"]
    print(name)
} catch {
    print(error)
}

Even better with safe unwrapping:

do {
    if let data = urlData, let jsonData = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? NSDictionary {
        if let user = jsonData["user"] as? NSDictionary, let name = user["name"] as? String {
            print(name)
        }
    }
} catch {
    print(error)
}

Note: in JSON, a dictionary is defined by {} and an array is defined by []. What you have here is a dictionary containing a dictionary, not an array (cf your question title).

Sign up to request clarification or add additional context in comments.

Comments

0

A great library to decode json is SwiftyJSON

you can get sub-scripted data from the json like so

import SwiftyJSON
if let dataFromString = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
    let json = JSON(data: dataFromString)
    let name = json["user"]["name"].string
    print(name)
}

1 Comment

Is there a way to do it without the library?
0

Use your code, then get the field from jsonData by this:

let name = jsonData.valueForKeyPath("user.name") as! String
let email = jsonData.valueForKeyPath("user.email") as! String

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.