I have a JSON String like this:
let stringArray = "[{\"url\":\"www.abc.com\",\"name\":\"benson\",\"age\":25},{\"url\":\"www.abc.com\",\"name\":\"tommy\",\"age\":23}]"
How can I remove one item(for example,tommy) in this string?
I tried to cast it to [[NSObject: AnyObject]] but always failed.
if let dictArray = stringArray as? [[NSObject: AnyObject]] {
} else {
println("failed") // print failed.
}
How can I get the result like this:
[{\"url\":\"www.abc.com\",\"name\":\"benson\",\"age\":25}]
Convert your string to array because its JSON String
var stringArray = "[{\"url\":\"www.abc.com\",\"name\":\"benson\",\"age\":25},{\"url\":\"www.abc.com\",\"name\":\"tommy\",\"age\":23}]"
var data : NSData = stringArray.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!
var error: NSError?
var array = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error) as Array<AnyObject>
println(array)
Output :
[{
age = 25;
name = benson;
url = "www.abc.com";
}, {
age = 23;
name = tommy;
url = "www.abc.com";
}]
Now perform delete operation
array.removeAtIndex(1)
println(array)
Output :
[{
age = 25;
name = benson;
url = "www.abc.com";
}]
First convert your json string to swift array or dictionary;
let stringArray:String = "[{\"url\":\"www.abc.com\",\"name\":\"benson\",\"age\":25},{\"url\":\"www.abc.com\",\"name\":\"tommy\",\"age\":23}]"
let data:NSData = stringArray.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!;
let dict:NSArray = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as! NSArray;
NSLog("dict \(dict)");
Maybe you can cast the original jsons string to the dictionary then pick up the keys what your needs. as the sample code like :
if let json = NSJSONSerialization.JSONObjectWithData("your string to NSDATA",options:NSJSONReadingOptions.AllowFragments,$error){
// checks the son type and make sure the operation perform to the NSDictionary
var d = json as! NSDictionary;
// Picks the the values your want from d
}
Related
I have made a struct that is helping me fetching info from a twitter json. The json has values such as text, which I am able to fetch without a problem, but it also has a dictionary names user and it has the string screen_name inside it.
How can I access that string?
Here is how I access the text string and how I fetch the user dictionary:
func parseTwitterJSON(_ data:Data) {
var jsonResult = NSArray()
do{
jsonResult = try JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.allowFragments) as! NSArray
} catch let error as NSError {
print(error)
}
var jsonElement = NSDictionary()
let twitterLocations = NSMutableArray()
for i in 0 ..< jsonResult.count{
jsonElement = jsonResult[i] as! NSDictionary
let twitterLocation = twitterLocationModel()
//the following insures none of the JsonElement values are nil through optional binding
if let lang = jsonElement["lang"] as? String,
let text = jsonElement["text"] as? String,
let user = jsonElement["user"] as? NSDictionary
{
twitterLocation.lang = lang
twitterLocation.text = text
twitterLocation.user = user
}
twitterLocations.add(twitterLocation)
}
DispatchQueue.main.async(execute: { () -> Void in
self.delegate.twitterDownloaded(items: twitterLocations)
})
}
To access the value of a key from a dictionary you would use
let myDictName : [String:String] = ["keyName" : "value"]
let value = myDictName["keyName"]
//value will be equal to "value"
Since you have the element user as an dictionary, you can just say
let userName = user["screen_name"]
{let doctorId: NSNumber = (self.selectedDoctor["id"] as? NSNumber)!
let referredTo:Dictionary = ["id":doctorId]
var postParams = [String : Any]()
postParams["referredTo"] = referredTo as AnyObject?
if self.mCase != nil{
if let patient:Patient = self.mCase.patient {
postParams["patient"] = ["id":patient.id!]
}
if let mCaseId:NSNumber = self.mCase.id{
postParams["medicalCase"] = ["id":mCaseId]
}
postParams["completeCase"] = self.completeCase as AnyObject?
postParams["includeAttachments"] = self.includeAttachment as AnyObject?
let visitDict = NSMutableDictionary ()
//let array = NSMutableArray()
for dict in self.visitIds {
let indx : Int! = (dict["visitID"] as? Int)!
visitDict["visit"] = ["id":indx!]
self.visitArray.add(visitDict)
}
if self.completeCase {
for visit in self.mCase.visits{
var id = (visit as AnyObject).id!
visitDict["visit"] = ["id": id!]
self.visitArray.add(visitDict)
}
}
postParams["referredVisits"] = self.visitArray
print(postParams["referredVisits"])
}
else{
let patient:Dictionary = ["id":self.patientId]
postParams["patient"] = patient as AnyObject?
}
marseResponse = MARSRequest.SendRequest("POST", postParams: postParams as [String : AnyObject]?,getParams: nil, service:.postpatientrererral)
}
This is how i am setting the parameters
Error Xcode is showing <__NSArrayM > while printing the array and please guide me for how to remove this. Please refer the below image. It was working fine in swift 2 but when I updated my code to swift 3 this issue appears. This is happening when I am sending the parameters in POST Method. And May be because of this I am not able to parse the data.
Data Parsing this is how i am parsing the data
How about converting your data to JSON?
For example, using standard class JSONSerialization:
let array = [
[
"visit": [
"id": 2625
]
]
]
let data = try JSONSerialization.data(withJSONObject: array, options: [])
let string = String(data: data, encoding: .utf8)
And then send string value?
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've been trying to get a JSON String to a Dictionary Value, and I can't get it to work, I'm getting an empty value. Before I tried to pull the data I checked that I got the all JSON, so obviously I'm doing something wrong here
let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options:
NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary
var items = [[String:String]()]
var item:AnyObject
var authorDictionary:AnyObject
for var i = 0; i < jsonResult["item"]?.count; i++ {
items.append([String:String]())
item = (jsonResult["items"] as? [[NSObject:AnyObject]])!
items[i]["content"] = item["content"] as? String
items[i]["title"] = item["title"] as? String
items[i]["publishedDate"] = item["published"] as? String
authorDictionary = item["author"] as! NSDictionary
items[i]["author"] = item["displayName"] as? String
}
println(items)
That's what I got as a result:
[[:]]
I am new to JSON, can someone explain me what I should do and what I did wrong?
You can iterate directly over jsonResult["items"] if it has the right type declared (array of dictionaries).
Then inside the loop you have to create a new dictionary each time, fill this dictionary with the data you grab from the JSON response, then you append the new dictionary to your items array of dictionaries:
var items = [[String:String]]()
for item in jsonResult["items"] as! [[String:AnyObject]] {
var newDict = [String:String]()
newDict["content"] = item["content"] as? String
newDict["title"] = item["title"] as? String
newDict["publishedDate"] = item["published"] as? String
newDict["author"] = item["displayName"] as? String
items.append(newDict)
}
As for authorDictionary, since it's a simple dictionary and not an array, if you assign it a value in the loop, it will be overwritten each time and all you'll have in the end is the author from the last object.
Check this out
let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary
var items = [[String:String]()]
var item:AnyObject
var authorDictionary:AnyObject
for var i = 0; i < jsonResult["items"]!.count; i++
{
items.append([String:String]())
item = (jsonResult["items"] as! [NSDictionary])[i]
items[i]["content"] = item["content"] as! NSString as String
items[i]["title"] = item["title"] as! NSString as String
items[i]["publishedDate"] = item["published"] as! NSString as String
authorDictionary = item["author"] as! NSDictionary
items[i]["author"] = authorDictionary["displayName"] as! NSString as String
}
println(items)
I have this JsonResponse:
...id = 7;
levels = (
{
name = "name";
"unique_id" = 23223;
},
{
name = "name";
"unique_id" = d32432;
},
{
name = "name";
"unique_id" = 324;
},
{
name = "name";
"unique_id" = 234;
}
);
I am using this to get result as a dictionary:
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as! NSDictionary
MY question is how can i parse the levels array - iterating the objects and getting the array size
Basically you just loop through them:
if(jsonResult)
{
let levels = jsonResult! as NSDictionary;
for item in levels {
let obj = item as NSDictionary
let name = obj["name"] as NSString;
let uniqueId = obj["unique_id"] as NSNumber;
}
}
I would advise to use type safety as much as you can when using JSON. Here is an (untested) example to show you how you can cast safely the data:
if let levels = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as? [[String: AnyObject]] {
for elem in levels {
let name = elem["name"] as? NSString
let uniqueId = elem["unique_id"] as? NSNumber
}
}