parsing json data in for loop statement using swift 2 - ios

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.

Related

how to get last element (array) in dictionary [string:Any]

i have a dictionary plist and i have to get an array from that dictionary which is in the last. i have to get that array in my table
var dict = [String: Any]()
func readAndWriteData(){
if let path = Bundle.main.path(forResource: "Property List", ofType: "plist") {
var dictionary : NSDictionary?
if var array = NSArray(contentsOfFile: path)?.firstObject as? [String:Any] {
// array["hello"] = "hello"
// i have get these value by using key of each values
print(array)
tableView.reloadData()
}else{
dictionary = NSDictionary(contentsOfFile: path)
dict = dictionary as! [String:Any]
print(dict["featureImageArray"])
}
}
}
First of all you are using pretty objective-c-ish API to get and parse the property list. Don't do that, use Swift native types and there is a dedicated class to (de)serialize property lists.
And there is no last item in the dictionary. You get the array by key featureImageArray
var array = [[String:Any]]()
func readAndWriteData(){
let url = Bundle.main.url(forResource: "Property List", withExtension: "plist")!
do {
let data = try Data(contentsOf: url)
let propertyList = try PropertyListSerialization.propertyList(from: data, format: nil) as! [String:Any]
array = propertyList["featureImageArray"] as! [[String:Any]]
tableView.reloadData()
} catch {
print(error)
}
}
A still better way is to use custom structs and PropertyListDecoder.

Accessing information within a NSDictionary

I am trying to parse out data from a NSDictionary but am having trouble. Whenever I try to access this information it prints nil.
NSDictionary:
{
"-LTR7P8PFWHogjlBENiJ" = {
filmid = 335983;
rating = "5.5";
review = Ehh;
};
}
CODE:
let dict = info.value as! NSDictionary
print(dict) //prints about NSDict
print(dict["review"] as? String) //prints nil
What would be the correct method to print "Ehh" from the NSDictionary?
You have outer dictionary wrapper of your searched result, with string key -LTR7P8PFWHogjlBENiJ
So your code currently searches key review in the outer dict.
You can get the review value as below,
typealias JSON = [String: Any]
let dictionary: JSON = [
"-LTR7P8PFWHogjlBENiJ": [
"filmid": 335983,
"rating": "5.5",
"review": "Ehh"
]
]
if let reivew = (dictionary.first?.value as? JSON)?["review"] as? String {
print(reivew)
}
For NSDictionary, you might have to use this as below,
let dict = info.value as! NSDictionary
if let reivew = (dict.allValues.first as? JSON)?["review"] as? String {
print(reivew)
}

Parse JSONArray contains JSONObjects Swift

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.

Swift JSON parsing and printing a specified value from an array

Hi I'm trying to get data from a certain JSON API. I can gat a snapshot of all values from the API, which is shown below. But I can't manage to put a specifiek row in a variable. This is the JSON form which I get. I want to print the "Description" value.Can someone help me with this?
And Hier is my code:
func apiRequest() {
let config = URLSessionConfiguration.default
let username = "F44C3FC2-91AF-5FB2-8B3F-70397C0D447D"
let password = "G23#rE9t1#"
let loginString = String(format: "%#:%#", username, password)
let userPasswordData = loginString.data(using: String.Encoding.utf8)
let base64EncodedCredential = userPasswordData?.base64EncodedString()
let authString = "Basic " + (base64EncodedCredential)!
print(authString)
config.httpAdditionalHeaders = ["Authorization" : authString]
let session = URLSession(configuration: config)
var running = false
let url = NSURL(string: "https://start.jamespro.nl/v4/api/json/projects/?limit=10")
let task = session.dataTask(with: url! as URL) {
( data, response, error) in
if let taskHeader = response as? HTTPURLResponse {
print(taskHeader.statusCode)
}
if error != nil {
print("There is an error!!!")
print(error)
} else {
if let content = data {
do {
let array = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
print(array)
if let items = array["items"] {
if let description = items["Description"] as? [[String:Any]]{
print(description as Any)
}
}
}
catch {
print("Error: Could not get any data")
}
}
}
running = false
}
running = true
task.resume()
while running {
print("waiting...")
sleep(1)
}
}
First of all the array is not an array and not AnyObject, it's a dictionary which is [String:Any] in Swift 3.
let dictionary = try JSONSerialization.jsonObject(with: content) as! [String:Any]
print(dictionary)
I don't know why all tutorials suggest .mutableContainers as option. That might be useful in Objective-C but is completely meaningless in Swift. Omit the parameter.
The object for key itemsis an array of dictionaries (again, the unspecified JSON type in Swift 3 is Any). Use a repeat loop to get all description values and you have to downcast all values of a dictionary from Any to the expected type.
if let items = dictionary["items"] as? [[String:Any]] {
for item in items {
if let description = item["Description"] as? String {
print(description)
}
}
}
Looks like items is an array that needs to be looped through. Here is some sample code, but I want to warn you that this code is not tested for your data.
if let items = array["items"] as? [[String: AnyObject]] {
for item in items {
if let description = item["Description"] as? String{
print("Description: \(description)")
}
}
}
This code above, or some variation of it, should get you on the right track.
use the SwiftyJSON and it would be as easy as json["items"][i].arrayValue as return and array with items Values or json["items"][i]["description"].stringValue to get a string from a row

How do I reference an object within an array within an object in xcode 8?

I'm looking to try and reference all "titles" within this json (link here) in xcode 8. The issue is there's an object and array that need to be referenced (i believe) before I can pull the title data, and I'm not sure how to do that.
So far this is what i've got:
func fetchFeed(){
let urlRequest = URLRequest(url: URL(string: "http://itunes.apple.com/us/rss/topalbums/limit=10/json")!)
let task = URLSession.shared.dataTask(with: urlRequest) { (data,response,error) in
if error != nil {
print(error)
return
}
self.artists = [Artist]()
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject]
if let feedFromJson = json["feed"]?["entry"] as? [[String : AnyObject]] {
for feedFromJson in feedsFromJson {
let feed = Feed()
if let entry = feedFromJson["entry"] as? String, let author = feedFromJson["domain"] as? String {
feed.entry = entry
article.headline = title
}
self.articles?.append(article)
}
}
DispatchQueue.main.async {
self.tableview.reloadData()
And thank you for your help in advance!
I'm working hard to try to understand what you need. If you want to get an Article array where the headline is the title label for the entry, here is how I cheated it out.
func articles(from json: Any?) -> [Article] {
guard let json = json as? NSDictionary, let entries = json.value(forKeyPath: "feed.entry") as? [NSDictionary] else {
return []
}
return entries.flatMap { entry in
guard let title = entry.value(forKeyPath: "title.label") as? String else {
return nil
}
var article = Article()
article.headline = title
return article
}
}
you call it as such
self.articles = articles(from: json)
NSDictionary has the method value(forKeyPath:) that is near magic. Calling json.value(forKeyPath: "feed.entry") returns an array of dictionaries. Each dictionary is an "entry" object in the json. Next, I map each entry to call entry.value(forKeyPath: "title.label") which returns a string.
If this is something more than a quick solution, then I would consider adding SwiftyJSON to your project.
func articles(from json: Any?) -> [Article] {
return JSON(json)["feed"]["entry"].arrayValue.flatMap { entry in
guard let title = entry["title"]["label"].string else {
return nil
}
var article = Article()
article.headline = title
return article
}
}
There is two kinds of titles.
the "feed" and the "entry".
if let entry = feedFromJson["entry"] as? String, let author = feedFromJson["domain"] as? String {
The practice of iOS is not this.
feedFromJson["entry"] is nil ,not a string . I guess you try to get the "feed" title.
if let entry = (json["feed"] as Dictionary)?["title"]
To get the "entry" title. Just traverse the array, and get the title.
let titleDict = feedFromJson["title"] as? Dictionary
let title = titleDict["title"] as? String
article.headline = title
Better to know the structure of the JSON data.
It's too quick.
if let feedFromJson = json["feed"]?["entry"] as? [[String :
AnyObject]] {
You should step by step.
if let feedFromJson = (json["feed"] as Dictionary)?["entry"] as? [[String : AnyObject]] {

Resources