let result = try?NSJSONSerialization.JSONObjectWithData(data,options:.MutableContainers)
How to take values from given JSON in swift2.3
({
FirstName:"sample"
LastName:"Data"
},
{
FirstName:"sample1"
LastName:"Data1"
})
How can I take value from first name and add to array swift 2.3 and Xcode8
Ok, try this with json is the json dictionary
let firstname = json["FirstName"] as! String
The following code converts your given json into string then uses NSJSONSerialization to parse your json and finally print the values of FirstName and Lastname
let jsonString = "[{\"FirstName\":\"sample\",\"LastName\":\"Data\"},{\"FirstName\":\"sample1\",\"LastName\":\"Data1\"}]"
if let serializedJsonArray = try? NSJSONSerialization.JSONObjectWithData(jsonString.dataUsingEncoding(NSUTF8StringEncoding)!, options: .MutableContainers),
let parsedJsonArray = serializedJsonArray as? [[String:AnyObject]]{
for jsonArray in parsedJsonArray {
if let firstName = jsonArray["FirstName"] as? String{
print(firstName)
}
if let lastName = jsonArray["LastName"] as? String{
print(lastName)
}
}
}
Hope this helps.
Related
hello i'm new to swift and I have responseJson from alamofire consist of jsonArray contain jsonObjects like this
[{"id":"1","name":"person1"},{"id":"2","name":"person2"}]
how i can parse it into array of this custom model
class Person {
var name : String
var id : String
}
i've done a much searching but can't find case identical to mine and i can't use Codable because i'm using xcode 8 and not able to upgrade my xcode version to 9 now
I'm getting the response like this
Alamofire.request(url).responseJSON{ response in
if(response.result.isSuccess)
{
if let jsonarray = response.result.value as? [[String: Any]]
{
//what to do here ?
}
}
}
if let jsonarray = response.result.value as? [[String: Any]]{
//what to do here ?
var persons:[Person] = []
for userDictionary in jsonarray{
guard let id = userDictionary["id"] as? String, let name = userDictionary["name"] as? String else { continue }
persons.append(Person(id, name))
}
//Persons complete.
}
Use guard else for the required variables.
If there are additional variables that could be optional, like var age:Int? in Person, you could do like this:
for userDictionary in jsonarray{
guard let id = userDictionary["id"] as? String, let name = userDictionary["name"] as? String else { continue }
let age = userDictionary["age"] as? Int
persons.append(Person(id, name, age))
}
#Tony,
In swift4 you can codable protocol to parsing the JSON that helps in writing generic code. Suppose if in future requirement came to add dob than its very simple.
And in swift3 you can use object mapper class for same.
If you need more help than please let me know.
I am developing a app using swift2 am parsing JSON data to a UITableView which works perfectly when click on the cell it moves to other view controller and fetching some data to label box. The problem is when I clicks any cells on the table view it fetching same data to a view controller I dont know how to parse the data into for loop statement.
Json data(data am recieving from the server):
{
item: [
{
name: "name1",
id: "1",
},
{
name: "name2",
id: "2"
}
]
}
Code what I have tried:
created outlet labelname and labelid
var arrDict :NSMutableArray=[]
let urlstring = "www.anything.com"
let url = NSURL(string: urlString)
let data = try? NSData(contentsOfURL: url, options: [])
let json = JSON(data: data)
print(json)
//it helps to print all the json data in console
Now help me work with forloop statement
Try this,it helps you:-
for (_, subjson): (String, JSON) in json["item"]{
print("YOUR SUBJSON VALUE>> \(subjson["name"].stringValue)")
}
var listArray = Dictionary<String, AnyObject>()
listArray["name"] = json["item"]?.valueForKey("name") as! Array
listArray["id"] = json["item"]?.valueForKey("id") as! Array
var name = [""]
var id = [""]
name = listArray["name"] as! Array
id = listArray["id"] as! Array
for i in 0..<name.count{
print(name[i])
print(id[i])
}
hope it will help
Try this way
let array = json["item"] as! [NSDictionary]
for dict in array {
let name = dict["name"] as! String
let id = dict["id"] as! String
}
i hope this will help you
take all json data in an NSArray(if data is in Array)
like this:
let arr = json as! NSArray
for i in 0...arr.count-1
{
let items = arr[i] as! NSMutableDictionary
var abc = items.valueForKey("name"))as! String
//Like this you can take all array values
}
hope it will help you.
I have the following data I received from Firebase. I have made my snapshotValue a NSDictionary.
self.ref.child("users").child(facebookID_Firebase as! String).observeSingleEvent(of: .value, with: { (snapshot) in
let snapshotValue = snapshot.value as? NSDictionary
print(snapshotValue, "snapshotValue")
//this line of code doesn't work
//self.pictureURL = snapshot["picture"]["data"]["url"]
}) { (error) in
print(error.localizedDescription)
}
I tried How do I manipulate nested dictionaries in Swift, e.g. JSON data? , How to access deeply nested dictionaries in Swift , and other solutions yet no luck.
How do I access the url value inside the data key AND the picture key?
I can make another reference in Firebase and get the value, but I'm trying to save another request. 😓
When you refrence to a key of a Dictionary in swift you get out an unwrapped value. This means it can be nil. You can force unwrap the value or you can use pretty if let =
this should probably work.
if let pictureUrl = snapshot["picture"]["data"]["url"] {
self.pictureURL = pictureUrl
}
Try using :-
if let pictureDict = snapshot.value["picture"] as? [String:AnyObject]{
if let dataDict = pictureDict.value["data"] as? [String:AnyObject]{
self.pictureURL = dataDict.value["url"] as! String
}
}
Inline dictionary unwrapping:
let url = ((snapshot.value as? NSDictionary)?["picture"] as? NSDictionary)?["url"] as? String
You can use the following syntax, that is prettier:
if let pictureDict = snapshot.value["picture"] as? [String:AnyObject],
let dataDict = pictureDict.value["data"] as? [String:AnyObject] {
self.pictureURL = dataDict.value["url"] as! String
}
}
let urlAsString = "https://drive.google.com/uc?export=download&id=0B2bvUUCDODywWTV2Q2IwVjFaLW8"
let url = NSURL(string: urlAsString)!
let urlSession = NSURLSession.sharedSession()
let jsonQuery = urlSession.dataTaskWithURL(url, completionHandler: { data, response, error -> Void in
do {
if let jsonDate = data, let jsonResult = try NSJSONSerialization.JSONObjectWithData(jsonDate, options: []) as? NSDictionary {
print(jsonResult)
}
} catch let error as NSError {
print(error)
}
})
jsonQuery.resume()
Okay so here i am receiving data from online json then storing it as NSDictionary in jsonresult . I need to get all keys and values as into two separate arrays ?
Basically i want this
jsonresult.allkeys --> String array
jsonresult.allvalues --> String array
You can use:
let keys = jsonResult.flatMap(){ $0.0 as? String }
let values = jsonResult.flatMap(){ $0.1 }
It is quite simple because you are using jsonResult as NSDictionary.
let dict: NSDictionary = ["Key1" : "Value1", "Key2" : "Value2"]
let keys = dict.allKeys
let values = dict.allValues
In you're case
let keys:[String] = dict.allKeys as! [String]
var values:[String]
if let valuesSting = dict.allValues as? [String] {
values = valuesSting
}
For anyone trying it with newer version Swift please use compactMap()instead of flatMap()
let keys = jsonResult.compactMap(){ $0.0 as? String }
let values = jsonResult.compactMap(){ $0.1 }
I am traversing some JSON Data where I need to access nested elements. Currently the easiest way is manually traverse the JSON Data as dictionaries like so
typealias JSON = AnyObject
typealias JSONDictionary = Dictionary<String, JSON>
typealias JSONArray = Array<JSON>
if let jsonData = data["preview"] as? JSONDictionary {
if let source: JSON = jsonData["images"] as? JSONArray {
if let images = source[0] as? JSONDictionary {
if let image = images["source"] as? JSONDictionary {
if let url = image["url"] as? String {
self.imageURL = url
getPhoto()
}
}
}
}
}
This seems unsustainable and the code is ugly.
Is there a better way to do this? How can I better traverse JSON data?
Try this using multiple levels seperated by commas:
if let
jsonData = data["preview"] as? JSONDictionary,
source = jsonData["images"] as? JSONArray,
images = source[0] as? JSONDictionary,
image = images["source"] as? JSONDictionary,
url = image["url"] as? String
{
self.imageURL = url
getPhoto()
}