How to conver my JSON to NSArray - ios

I'm new to Swift, i started learning on the new Swift 3
I've this as NSArray
var arrayName: NSArray = NSArray()
arrayName = ["name 1","name 2","name 3","name 4","name 5"]
The tableview currently prints those items above.
I want to get JSON online from http://api.androidhive.info/contacts/
and append name items to be the content of my NSArray arrayName

So first get the json data in a shared url session. Make sure to check for the success flag in the completion closure. Once you've got the data you can deserialize it with the JSONSerialization class, https://developer.apple.com/documentation/foundation/jsonserialization. So now you have the json in an object. Now you can convert it to a dictionary. In the dictionary traverse into "contacts" with the dictionary["contacts"] syntax. Next, cast the new object as a [[String: AnyObject]] which means array of dictionaries. From there, you can loop through and get the name property. Note: instead of casting the object as [[String: AnyObject]] you could also cast it as! NSArray.

Related

Nested Dictionary in iOS Swift

I want to save a data in a dictionary in below format and then have to convert it into json.
[{"id":"1",
"name":[{"id":"2","name":"k"},{"id":"6","name":"kk"}]",
"pass":"123"},
{"id":"2",
"name":[{"id":"2","name":"k"},{"id":"6","name":"kk"}]",
"pass":"234"}
]
It got dictionary and single strings both within a dictionary. Here is what I'm trying, but unable to get the desirable result.
var myDictionary = Dictionary<String, AnyObject>()
let arrOfData = [["id":"1","pass":"123","name":[["id":"2","name":"k"],["id":"6","name":"kk"]]],
["id":"2","pass":"234","name":[["id":"2","name":"k"],["id":"6","name":"kk"]]]]
Here u can see the array of dictionary like Array<Dictionary,AnyObject> if you want to store in a single dictionary you can use it like let dict2 = ["data":arrOfData] Now this will convert into a single dictionary.

Swift NSDictionary get 0th value without knowing key name

I have an NSDictionary that has a key like messageID5 and the value has three key/value pairs.
I know the NSDictionary only has 1 value in it because I limited my query to 1. But I don't know the name of the key. I just want the value, but I can't access it like an array [0]. You can access it just fine in PHP or Python. I've been trying a lot of different solutions for this basic problem, but a lot of them seem overly messy. anyValue[0] gives me a type error.
If you don't know your dictionary keys, you can get your NSDictionary allKeys.first property or allValues.first:
let dict = NSDictionary(dictionary: ["a":["b":1]])
let subDict = dict[dict.allKeys.first] as? [String:Any] ?? [:] // ["b": 1]
// or
let subDict = dict.allValues.first as? [String:Any] ?? [:] // ["b": 1]
The first thing to acknowledge is that key/value pairs in dictionaries does not maintain any specific order - this is required for an optimization in access to the contents of this structure.
As for your case if you're 100% sure you'll have only one value inside your dictionary you can use .allValues.first to retrieve the contained value. If your know that the type of your value is NSDictionary the whole code may look like this:
let childDictionary = rootDictionary.allValues.first as? NSDictionary
I suggest using (dictionary as Dictionary).values.first. That returns an optional, since it can fail if the dictionary is empty.
(Note that I edited this answer to cast the dictionary from an NSDictionary to a Dictionary so you an use the values property. NSDictionary doesn't have a values property, but Dictionary does.)

iOS Swift Updating Dictionary In An Array

I have an array of dictionaries inside a dictionary. I initialize it like this:
var fillups:[NSMutableDictionary] = []
Then I load it like this:
fillups = userDefaults.object(forKey: car) as! NSArray as! [NSMutableDictionary]
Then when I try to update a dictionary element in the array I get the "mutating method sent to immutable object" error. Here's my code to update the record:
let dict=fillups[row]
dict.setValue(odometerField.text, forKey: "odometer")
dict.setValue(gallonsField.text, forKey: "gallons")
fillups[row]=dict
The error occurs in my first setValue line.
Objects that you retrieve from NSUserDefaults are immutable even if they were mutable when they were inserted. You need to take the immutable objects you get from defaults and create mutable versions of them. You also shouldn't force unwrap everywhere if you don't want your app to crash.
if let array = userDefaults.object(forKey: car) as? [NSDictionary] {
fillups = array.map { ($0.mutableCopy() as! NSMutableDictionary) }
}
You also don't need the fillips[row] = dict line since NSMutableDictionary is a reference type and editing the reference you pull out of the array is already editing the one inside the array.
If you want to mutate your dict, you need to declare it with 'var' not with 'let'; 'let' is for constants. Also fix the unwrapping problems pointed out by the comment
let dict=fillups[row]
should be
var dict=fillups[row]

How do you Parse an Array of Dictionaries in Swift?

I'm new to swift and I am having difficulty parsing an array the array looks like this
MyArray [
[0]9keyValuePairs
[1]9keyValuePairs
]
I would like to add "MyArray.(0).ValueForKey:"Name" " to a UITableViewCell, but I can't quite figure out the correct syntax.
How is your array declared? If it is a array of something generic, ie [AnyObject] then you need to tell the type checker that the object in the array is a dictionary by casting it, otherwise you wont be able to access it as a dictionary.
If it is explicitly declared as an array of dictionaries ie [[String:AnyObject]] , then you just need to access the element in the array that you want, and then access the dictionary element you are interested in.
array[0] //how to get something out of an array
dictionary[key] //how to get something out of a dict
array[0][key] //how to get something out of an array of dicts
// if your array contents need to be cast, safely cast it using optional unwrapping
if let dict = array[0] as? [String:AnyObject] {
dict[key]
}

Could not cast value of type '__NSArrayM' to 'NSDictionary'

I have a json.I am trying to parse that with that code.But its says
Could not cast value of type '__NSArrayM' to 'NSDictionary'
do {
let dataDictionary: NSDictionary = try NSJSONSerialization.JSONObjectWithData(responseObject as! NSData, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary // <------ Error
if let customerArray = dataDictionary.valueForKey("cart") as? NSArray {
for js in customerArray {
let nameArray = js.valueForKey("name")
let idArray = js.valueForKey("id")
}
}
}
Thank you for your helps
The root object in your data is an array, not a object (dictionary).
You need to dynamically decide how to handle your JSON depending on the deserialized object.
What it's telling you is that the JSON object that you're parsing is not a dictionary, it's an array. So if you change it so that you treat its value as an array instead of a dictionary, you'll be able to iterate over that.
You need to reevaluate your JSON to ensure that it's structured the way you think it is. It would also be useful if you posted the JSON that you're trying to parse so that we can see it's structure as well.

Resources