Can't create dictionary from json in swift [duplicate] - json

This question already has answers here:
How to convert a JSON string to a dictionary?
(10 answers)
Closed 6 years ago.
I Have this json object which is downloaded by dataTaskWithRequest, i download it and serialize it like this:
let json = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as? [String:AnyObject]
completion(json)
then the completion looks like this:
(let json) in
if let dict = JSON{
completion(dict)
}
and last completion looks like this:
(let response) in
dispatch_async(dispatch_get_main_queue()){
if let resp = response{
if resp["status"] as? Int == 0{
let user = resp["user"]
if let dict = user{
print(dict)
}
}
}
}
problem is that, it returns object like this:
{"created": "2016-06-01T10:49:54.096000",
"data_source": "1",
"display_name": "My Name",
"email": "Some#string.com",
"fb_id": "",
"first_name": "My",
"gender": "0",
"google_id": "",
"id": "SomeId",
"last_name": "Name",
"phone": "Number",
"updated": "2016-06-01T10:49:54.096000"}
when i try to cast this object in [String:AnyObject] it returns nil, and i can't get the values from this last object, can anybody help me with this, i've been trying to do this for like 4 hours and couldn't get it done

try this :
if let dictString = user as? String{
if let data = dictString.dataUsingEncoding(NSUTF8StringEncoding){
let dic = try! NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
print(dic)
}
}

Related

Parsing JSON response in Swift 3

I've got an API endpoint that returns JSON in the following format:
[
{
"id": "1",
"name": "John"
},
{
"id": "2",
"name": "Jane"
},
{
"id": "3",
"name": "Nick"
}
]
I am trying to parse this in Swift 3, but I can only find examples to parse JSON formatted like so:
{
"blogs": [
{
"needspassword": true,
"id": 73,
"url": "http://remote.bloxus.com/",
"name": "Bloxus test"
},
{
"needspassword": false,
"id": 74,
"url": "http://flickrtest1.userland.com/",
"name": "Manila Test"
}
],
"stat": "ok"
}
, which has an extra level above what mine does.
So, where examples I've seen are simply parsing their data like jsonResponse["blogs"], I can't do that as my format is different.
How can I parse the format I've got, or how can I return a format that is easier to parse?
Any suggestions appreciated, thanks!
You can just do the following :
let data = // Data received from WS
do {
let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions()) as? [[String : String]]
//json is now an array from dictionary matching your model
}
catch {
//handle error
}
This will parse it when placed in the network call.
do {
let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions()) as! [[String : AnyObject]]
let firstPerson = json[0]
print(firstPerson)
let id = firstPerson["id"] as! String
print(id)
let name = firstPerson["name"] as! String
print(name)
} catch {
//handle error
}
Also, I tend to be against advising third party libraries, but SwiftyJSON is an exception I make. If you want to try it, add this to your pod file:
pod SwiftyJSON', '3.0.0'
Documentation: https://github.com/SwiftyJSON/SwiftyJSON
EDIT - Answering Comment:
Replacement line:
if let id = firstPerson["id"] as? String {
print(id)
}
Replacement line (if you need to hold on to the value):
var thisId: String?
if let id = firstPerson["id"] as? String {
thisId = id
}
print(thisId ?? "")
i don't really know swift but there might be the equivalent of ajax json encoding (server side you json_encode your array and client side you json_decode the response)
the idea is to have the same formatter that encodes and decodes the data

Read GeoJSON data from MongDB in Xcode 8.1 Swift 3?

I have a NodeJS API that queries a MongoDB cluster and returns nearby data in the following format. The issue is I can't enumerate the locations with Swift 3 and XCode 8.1.
[
{
"_id": "57b03fa32c6835946afd358c",
"location": {
"coordinates": [
144.2,
-34
],
"elevation": "1",
"type": "Point"
},
"name": "Resource 01",
"url": "http://www.url.com/Resource01.html"
},
{
"_id": "34b03fa32c6835946afd358c",
"location": {
"coordinates": [
154.2,
-35.3
],
"elevation": "1",
"type": "Point"
},
"name": "Resource 02",
"url": "http://www.url.com/Resource02.html"
}
]
This is my Query code.
let json = try! JSONSerialization.jsonObject(with: data)
print(json)
if let statusesArray = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [[String: AnyObject]],
let jsonbranch = statusesArray?[0] as? [String: AnyObject],
let therecord = jsonbranch["_id"] as? String {
print ("_id: " + therecord)
}
I tried to use SwiftyJSON but it does not work either?
Solved:
if let jsonBranch = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [[String: AnyObject]],
let name = jsonBranch?[0]["name"] as? String {
print ("name: " + name)
}
if let jsonBranch = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [[String: AnyObject]],
let name = jsonBranch?[1]["name"] as? String {
print ("name: " + name)
}

Crash : Convert dictionary to Json string in Swift 3

I'm trying to convert my swift dictionary to Json string but getting strange crash by saying
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (_SwiftValue)'
My code:
let jsonObject: [String: AnyObject] = [
"firstname": "aaa",
"lastname": "sss",
"email": "my_email",
"nickname": "ddd",
"password": "123",
"username": "qqq"
]
do {
let jsonData = try JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted)
// here "jsonData" is the dictionary encoded in JSON data
let decoded = try JSONSerialization.jsonObject(with: jsonData, options: [])
// here "decoded" is of type `Any`, decoded from JSON data
// you can now cast it with the right type
if let dictFromJSON = decoded as? [String:String] {
// use dictFromJSON
}
} catch {
print(error.localizedDescription)
}
Please help me!
Regards.
String is not of type AnyObject. Objects are reference types, but String in swift has value semantics. A String however, can be of type Any, so the code below works. I suggest you read up on reference types and value semantic types in Swift; its a subtle but important distinction and its also different from what you expect from most other languages, where String is often a reference type (including objective C).
let jsonObject: [String: Any] = [
"firstname": "aaa",
"lastname": "sss",
"email": "my_email",
"nickname": "ddd",
"password": "123",
"username": "qqq"
]
do {
let jsonData = try JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted)
// here "jsonData" is the dictionary encoded in JSON data
let decoded = try JSONSerialization.jsonObject(with: jsonData, options: [])
// here "decoded" is of type `Any`, decoded from JSON data
// you can now cast it with the right type
if let dictFromJSON = decoded as? [String:String] {
print(dictFromJSON)
}
} catch {
print(error.localizedDescription)
}

Parse twitter trend api results in swift

I using twitter trend api to get the name of all the trends.
I have the following setup:
let url = "\(APIConstants.Twitter.APIBaseURL)1.1/trends/place.json?id=1"
let client = TWTRAPIClient()
let statusesShowEndpoint = url
let params = ["id": "20"]
var clientError : NSError?
let request = client.urlRequest(withMethod: "GET", url: statusesShowEndpoint, parameters: params, error: &clientError)
client.sendTwitterRequest(request) { (response, data, connectionError) -> Void in
if connectionError != nil {
print("Error: \(connectionError)")
}
do {
let json = try JSONSerialization.jsonObject(with: data!, options: [])
} catch let jsonError as NSError {
print("json error: \(jsonError.localizedDescription)")
}
}
and after the call, json has the following data:
(
{
"as_of": "2012-08-24T23:25:43Z",
"created_at": "2012-08-24T23:24:14Z",
"locations": [
{
"name": "Worldwide",
"woeid": 1
}
],
"trends": [
{
"tweet_volume": 3200,
"events": null,
"name": "#GanaPuntosSi",
"promoted_content": null,
"query": "%23GanaPuntosSi",
"url": "http://twitter.com/search/?q=%23GanaPuntosSi"
},
{
"tweet_volume": 4200,
"events": null,
"name": "#WordsThatDescribeMe",
"promoted_content": null,
"query": "%23WordsThatDescribeMe",
"url": "http://twitter.com/search/?q=%23WordsThatDescribeMe"
},
{
"tweet_volume": 2200,
"events": null,
"name": "Sweet Dreams",
"promoted_content": null,
"query": "%22Sweet%20Dreams%22",
"url": "http://twitter.com/search/?q=%22Sweet%20Dreams%22"
}
]
}
)
From the above json data, i want to store all the name inside trends in an array in swift.
There is some data checking and casting you need to do to make sure you're getting back the data in the structure you'd expect, and then from there its simple iteration. Something along these lines should get you going:
let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:Any]
var names = [String]()
if let trends = json?["trends"] as? [[String:Any]] {
for trend in trends {
if let name = trend["name"] as? String {
names.append(name)
}
}
}
Note the various as? type checks to iterate over the structure safely. For a more in-depth review of cleanly working with JSON in Swift including reading the data in to type-safe structs, check out this official blog post from Apple.

Unwrapping Json Swift (found nil)

i currently trying to decode Json in Xcode, but i not succed to get one of them.
This is what i get :
[
{
"id": "1",
"title": "bmw",
"price": "500.00",
"description": "330",
"addedDate": "2015-05-18 00:00:00",
"user_id": "1",
"user_name": "CANOVAS",
"user_zipCode": "32767",
"category_id": "1",
"category_label": "VEHICULES",
"subcategory_id": "2",
"subcategory_label": "Motos",
"bdd": {}
}
"pictures":
[
{ "name": "http://cars.axlegeeks.com/sites/default/files/4315/media/images/2014_BMW_Z4_sDrive28i_3790993.jpg"
}
]
}
]
And i want to get the value of "name" for the "Pictures" lines but i have the error "unexpectedly found nil while unwrapping value".
For the others values i proceed this way :
let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as! NSDictionary
//Browse into JSON to get datas
let resp = jsonData["0"] as! NSDictionary
let user_nameR = resp["user_name"] as! String
let user_zipCodeR = resp["user_zipCode"] as! String
let titleR = resp["title"] as! String
let priceR = resp["price"] as! String
let descriptionR = resp["description"] as! String
Thank's for your help !
Pictures is in not in the subdictionary your other values are. This should work, but you should check all values if they are nil before you force cast them.
if let pictureArray = jsonData["pictures"] as? NSArray
{
if let pictureDict = pictureArray.firstObject as? NSDictionary
{
if let pictureName = pictureDict.objectForKey("name") as? String
{
NSLog("Picture name: %#", pictureName)
}
}
}
jsonData contains two sub-dictionaries, one without a key and one with key 'pictures'. Pictures is an array containing one sub-dictionary.