Working With Json in swift 3 - arrays

I want to get long_name from this JSON file I can just access 'results' with this code:
let url = URL(string: "https://maps.googleapis.com/maps/api/geocode/json?latlng=35.7229513,51.3566039&language=fa&key=AIzaSyBXOPT1jEYizWZHOKLwv4dhacgYTcmn3I4")!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print(error!)
}
else{
if let urlcontent = data {
do{
let jsonResult = try JSONSerialization.jsonObject(with: urlcontent, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String:Any]
print(jsonResult["results"]!)
if let jsonResult = jsonResult["results"] as? [String: Any] {
if let address_components = jsonResult["address_components"] as? [String: Any] {
print(address_components)
if let long_name = address_components["long_name"] as? [String: Any] {
print(long_name)
}
}
}
}
catch{
print("json failed")
}
}
}
}
task.resume()
But I'm just getting result this is my JSON file:
https://maps.googleapis.com/maps/api/geocode/json?latlng=35.7339859%2C51.3393980&sensor=true_or_false&language=fa

Your result key contains Array as value not Dictionary so simply change [String:Any] to [[String:Any]] and then access address_components from the each dictionary objects of resultsArray, now address_components is also array of dictionary and long_name is inside that dictionary. So try like this.
if let resultsArray = jsonResult["results"] as? [[String: Any]] {
for dic in resultsArray {
if let addressArray = dic["address_components"] as? [[String:Any]] {
for address in addressArray {
if let longName = address["long_name"] as? String {
print(longName)
}
}
}
}
}

Related

How to append JSON data into an array in swift

Hello Guys i need help I'm trying to save json data in an array but i'm not getting it properly can anyone help me here is the complete code
let url = URL(string: "http://localhost:3000/liveData/device/20042")
URLSession.shared.dataTask(with: url!, completionHandler: {
(data, response, error) in
if(error != nil){
print("error")
}else{
do{
let json = try JSONSerialization.jsonObject(with: data!, options:[]) as! [[String: Any]]
print(json)
for item in json {
if let title = item["BV"] as? String {
self.userIdArray.append(title)
}
if let title = item["BC"] as? String {
self.userIdArray.append(title)
}
if let title = item["SV"] as? String {
self.userIdArray.append(title)
}
if let title = item["SC"] as? String {
self.userIdArray.append(title)
}
}
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}catch let error as NSError{
print(error)
}
}
}).resume()
I want to save json data in userIdArray can anyone help me, Thank you.
{
"SV" : 0,
"SC" : 0,
"BV" : 14.807,
"BC" : 0.024,
}
This is the output json

Getting Data from JSON Swift

Can Anyone Help me with this
my data after parsing a JSON URL is
{
AREA = (
{
"area_name" = "Bhaktamadhu Nagar";
"city_id" = 4;
id = 31;
price = "100.00";
},
{
"area_name" = "Gandamunda";
"city_id" = 4;
id = 32;
price = "100.00";
}
);
}
and there is a lot more.
I want to fetch only area_name and price values in an array
my code is something like that
do {
let parsedData = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! NSDictionary
print(parsedData)}
I am getting my Upper format in the parsedData
What is the exact code for getting my area_name and price which should store in two separate arrays as aname[] and price[]
Please don't mark it as a duplicate already searched a lot before posting this.
Your JSON data is converted into [String: AnyObject].
AREA data is [[String: AnyObject]] so create a [String: AnyObject] array. and getting a one by one value from array.
How to fetch JSON data from a url using URLSession?
try this code. it's helpfull
URLSession.shared.dataTask(with: url) { (data, response, error) in
if let jsonData = data {
do {
let parsedData = try JSONSerialization.jsonObject(with: jsonData, options: .mutableLeaves) as! [String: AnyObject]
if let area = parsedData["AREA"] as? [[String: AnyObject]] {
for a in area {
areaNameArr.append(a["area_name"])
priceArr.append(a["price"])
print(a)
}
}
}
catch let error {
debugPrint(error)
}
}
else {
debugPrint(error as Any)
}
}.resume()
Use the SwiftyJSON Lib.
It’s easy and fast.
I am using it and it’s very helpful in this way:
let session = URLSession(configuration: URLSessionConfiguration.ephemeral)
self.Task = session.dataTask(with: RequestLink as URLRequest , completionHandler: { (data,response,error) in
if error != nil {
print(error as Any)
}
let ReadJson4Rest = JSON(data: data!)
if let Rest_Details = ReadJson4Rest["Result"].array{
for Details in Rest_Details {
let Comment = Details.dictionaryValue["Comment"]!
let UserName = Details.dictionaryValue["User_ID"]!
if Comment != nil {
let FirstChar = UserName.description.characters.first
self.GetUserImage(UserName: UserName.string! ,AlphabetCat: (FirstChar?.description)!)
DispatchQueue.main.async {
self.CommentValue.append(Comment.string!)
self.UserNames.append(UserName.string!)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "Load"), object: nil)
}
}
}
}
})
self.Task?.resume()
}

"print array in main thread swift3 Xcode 8"

I learn swift not long ago and i have some problem in this code print array:
class InitController: UIViewController {
public var initdata = [(id: String, name: String)]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
print("initdata", initdata)
init_auth()
}
func init_auth(){
let json: [String: Any] = ["token": UserDefaults.standard.value(forKey: "token"), "id":UserDefaults.standard.value(forKey: "id")]
//let jsonData = try? JSONSerialization.data(withJSONObject: json)
let jsonData = try? JSONSerialization.data(withJSONObject: json)
let url = "http://some_ip/api"
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "POST"
request.httpBody = jsonData
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
//print(jsonData)
let task = URLSession.shared.dataTask(with: request) { data, responce, error in guard let data = data, error == nil else {
print(error?.localizedDescription ?? "No data")
return
}
let responceJSON = try? JSONSerialization.jsonObject(with: data, options: [])
if let responceJSON = responceJSON as? [String: Any]{
let s = responceJSON["specialities"] as? NSDictionary
let d = s?["items"] as! NSArray
for i in d {
let f = i as? NSDictionary
self.initdata.append((id: f?["id"] as! String, name: f?["name"] as! String))
}
}
}
print("list", self.initdata)
task.resume()
}
}
initdata is empty array, but I get some json file and append this array. I try print initdata, but this array is nil. I think maybe problem in thread, but I don't know how realize this.
Try this -
func init_auth(){
let json: [String: Any] = ["token": UserDefaults.standard.value(forKey: "token"), "id":UserDefaults.standard.value(forKey: "id")]
//let jsonData = try? JSONSerialization.data(withJSONObject: json)
let jsonData = try? JSONSerialization.data(withJSONObject: json)
let url = "http://some_ip/api"
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "POST"
request.httpBody = jsonData
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
//print(jsonData)
let task = URLSession.shared.dataTask(with: request) { data, responce, error in guard let data = data, error == nil else {
print(error?.localizedDescription ?? "No data")
return
}
let responceJSON = try? JSONSerialization.jsonObject(with: data, options: [])
if let responceJSON = responceJSON as? [String: Any]{
let s = responceJSON["specialities"] as? NSDictionary
let d = s?["items"] as! NSArray
for i in d {
let f = i as? NSDictionary
self.initdata.append((id: f?["id"] as! String, name: f?["name"] as! String))
}
print("list", self.initdata)
}
}
task.resume()
}

Swift 3 JSON Array to Dictionary

I have a JSON result from Alamofire and SwiftyJSON and am trying to create a dictionary from it to create an array
JSON Result
JSON: [
{
"p_589b6a49a0bfd" : {
"path" : "\/uploads\/588fa43eba3c9\/588fa43eba3c9_1486580297.jpg",
"likes" : "0",
"userid" : "588fa43eba3c9",
"caption" : "Bae",
"comments" : "0",
"date" : "1486580297"
}
},
{
"p_589b7f1c540f1" : {
"path" : "\/uploads\/588fa43eba3c9\/588fa43eba3c9_1486585628.jpg",
"likes" : "0",
"userid" : "588fa43eba3c9",
"caption" : "Hot stuff bitch ",
"comments" : "0",
"date" : "1486585628"
}
}
]
Request/Response
Alamofire.request(BASE_URL + "index.php/feed/build", method: .get, headers: headers).responseJSON { response in
switch response.result {
case .success(let value):
let json = JSON(value)
print("JSON: \(json)")
case .failure(let error):
print(error)
}
}
I have then set up a simple class called 'FeedPost' which will store each of the elements in JSON response (this is the function in the FeedPost class)
init(postid: String, postData: Dictionary<String, AnyObject>) {
self._postid = postid
if let caption = postData["caption"] as? String {
self._caption = caption
}
if let path = postData["path"] as? String {
self._path = path
}
if let likes = postData["likes"] as? Int {
self._likes = likes
}
if let comments = postData["comments"] as? Int {
self._comments = comments
}
if let userid = postData["userid"] as? String {
self._userid = userid
}
if let date = postData["date"] as? String {
self._date = date
}
}
I need to somehow cycle through the JSON to create a dictionary to pass to FeedPost then add each FeedPost to another array called Posts during the request. The string that starts with 'p_' I want to use as the postid
With Alamofire response you have used SwiftyJSON and with your FeedPost init you are using swift native dictionary. So I'm suggesting you to either work with SwiftyJSON or with swift's native type. Since you have already added init with dictionary I'm answering your answer with native type.
Alamofire.request(BASE_URL + "index.php/feed/build", method: .get, headers: headers).responseJSON { response in
switch response.result {
case .success(let value):
If let dic = value as? [String: Any],
let array = DIC["JSON"] as? [[String: Any]] {
for item in array {
for (key, value) in item {
If let subDic = value as? [String: Any] {
let obj = FeedPost(postid: key, postData: subDic)
}
}
}
}
print("JSON: \(json)")
case .failure(let error):
print(error)
}
}
Note: Correct Dictionary notation for JSON in swift 3 is [String: Any] not [String: AnyObject] so change your init parameter postData's type to [String: Any].
Below is the code which can be used for your case, This code is copied from playgrounds.
import UIKit
typealias JSONDictionary = [String: AnyObject]
class Post {
let id: String
let userId: String?
let date: Double?
let caption: String?
let comments: Double?
let likes: Double?
let path: String?
init?(with dictionary: JSONDictionary) {
guard let postId = dictionary.keys.first, let postInfo = dictionary[postId] as? JSONDictionary else { return nil }
self.id = postId
self.userId = postInfo["userid"] as? String
self.date = postInfo["date"] as? Double
self.caption = postInfo["caption"] as? String
self.comments = postInfo["comments"] as? Double
self.likes = postInfo["likes"] as? Double
self.path = postInfo["path"] as? String
}
}
Parsing JSON array will be like this.
case .success(let value):
let jsonArray = value["JSON"] as? [JSONDictionary]
let posts = jsonArray?.flatMap(Post.init(with:))
print("Posts \(posts)"
case .failure: break
I have tried this using a local JSON file in a Playgrounds & code was something like this.
let url = Bundle.main.url(forResource: "data", withExtension: "json")
let data = try! Data(contentsOf: url!)
let jsonArray = try! JSONSerialization.jsonObject(with: data , options: .allowFragments) as? [JSONDictionary]
let posts = jsonArray?.flatMap(Post.init(with:))

How can I get data from JSON array in SWIFT?

from this link I would like to get the commonName
I tried this but it didn't work?!
let commonName = object["toLocationDisambiguation"][0]["disambiguationOptions"][1]["place"][2]["commonName"].stringValue
Option 1 (Normal)
if let toLocationDisambiguation = object["toLocationDisambiguation"] as? Dictionary<String, AnyObject> {
if let disambiguationOptions = toLocationDisambiguation["disambiguationOptions"] as? Array<AnyObject> {
if let first = disambiguationOptions.first as? [String: AnyObject] {
if let place = first["place"] as? [String: AnyObject] {
let commonName = place["commonName"] as! String
print("Common Name: ", commonName)
}
}
}
}
Option 2 (Type Aliases)
typealias MyDictionary = [String: AnyObject]
typealias MyArray = [MyDictionary]
if let toLocationDisambiguation = object["toLocationDisambiguation"] as? MyDictionary {
if let disambiguationOptions = toLocationDisambiguation["disambiguationOptions"] as? MyArray {
if let first = disambiguationOptions.first {
if let place = first["place"] as? MyDictionary {
let commonName = place["commonName"] as! String
print("Common Name: ", commonName)
}
}
}
}
Option 3 (SwiftyJSON for Objective-C like syntax)
Take a look at SwiftyJSON.
let object = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! Dictionary<String, AnyObject>
let json = JSON(object)
let commonName = json["toLocationDisambiguation"]["disambiguationOptions"][0]["place"]["commonName"].stringValue
print("Common Name: ", commonName)

Resources