I receive JSON objects that looks like the one below. How can I convert it into a format that is easily handled by Swift 2.1 ? I will receive several of these and have to put them into an array and sort by createdAt.
Optional({
comment = "<null>";
completedAt = "<null>";
createdAt = "2015-11-02 15:01:04 +0000";
paid = 1;
paidAt = "2015-11-02 15:01:04 +0000";
startedAt = "<null>";
state = request;
type = doctor;
user = KTsCySacEAiz3eDnf;
userdata = {
birthdate = "<null>";
gender = "<null>";
};
})
As in the title you say you expect a Dictionary, you can get one by simply serializate the json and cast it to a Dictionary.
do{
let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
}catch{
print("Something went wrong")
}
Where data is you json content as NSData. If you get a String you can easily convert it
let data = text.dataUsingEncoding(NSUTF8StringEncoding)
Related
json comes in and is an array of dictionary:
let dict = try JSONSerialization.dictionary(data: data, options: .allowFragments)
(key: contact_383348580, value: {
email = "r#c.com";
"first_name" = Jon;
"last_name" = B;
tags = "";
})
(key: contact_445575065, value: {
email = "n.w#s.com";
"first_name" = "<null>";
"last_name" = "<null>";
tags = "";
})
Trying to map this to a User class (and then sort alpha by first name(?)) and then populate a tableview.
I'm all obj-c but trying to add this feature in my objc project through swift to improve my skills incrementally. But googling returns all different ways with different swift versions that don't seem to work (or frankly make sense to me anyway but I'll get there).
Currently I can create users but the names are empty.
for objects in dict {
print(objects)
let first = dict["first_name"] as? String
let last = dict["last_name"] as? String
let name = "\(first ?? "asas") \(last ?? "sdasd")"
let object = User(username: name)
contacts.append(object!)
}
print(" contacts \(contacts)")
You say you have an array of dictionaries and if that is correct then you have fooled yourself with the naming of your variables because dict is an array and objects a dictionary. I assume your code doesn't compile?
What about this
let array = try JSONSerialization.dictionary(data: data, options: .allowFragments)
for dict in array {
let first = dict["first_name"] as? String ?? "asas"
let last = dict["last_name"] as? String ?? "sdasd"
let name = "\(first) \(last)"
let object = User(username: name)
contacts.append(object)
}
This is my JSON data, how can I get src data in 0 in pickArray?
"pickArray" : "{\"0\":{\"src\":\"https:\/\/fb-s-d-a.akamaihd.net\/h-ak-xpl1\/v\/t1.0-9\/p720x720\/18010403_1525007564199498_8009700960533638318_n.png?oh=25dbc9c1522dcfdd1d15cdd3e8c0c7da&oe=59997685&__gda__=1502470695_f212ade003e9b1c4ddc6a3ab6cc9e7e7\",\"width\":720,\"height\":720}}"
If I do it like this:
let dataArray = json["pickArray"]
print("dataArray = ",dataArray)
dataArray = {"0":{"src":"https://fb-s-d-a.akamaihd.net/h-ak-xpl1/v/t1.0-9/p720x720/18010403_1525007564199498_8009700960533638318_n.png?oh=25dbc9c1522dcfdd1d15cdd3e8c0c7da&oe=59997685&__gda__=1502470695_f212ade003e9b1c4ddc6a3ab6cc9e7e7","width":720,"height":720}}
But if I do it like this, show null:
let srcArray = dataArray["0"]
print("srcArray = ",srcArray)
I'm using swift3.0
Its looks like that with key pickArray you are having JSON response in String so get that string and convert it data and get JSON from it and then get src from it.
let stringResponse = json["pickArray"].stringValue
if let data = stringResponse.data(using: .utf8) {
let pickArray = JSON(data: data)
//Now access the pickArray to get the src
var sortedKeys = [String]()
if let allKeys = pickArray.dictionaryObject {
sortedKeys = Array(allKeys.keys).sorted { $0.compare($1, options: .numeric) == .orderedAscending }
}
for key in sortedKeys {
print(pickArray[key]["src"].stringValue)
print(pickArray[key]["width"].intValue)
print(pickArray[key]["height"].intValue)
}
}
let srcArray = dataArray["0"].dictionaryObject!
print("srcArray = \(srcArray)")
Now you can access element of "0" value as like below. Hope this work for you.
let jsonScr = JSON(srcArray)
let srcURL = jsonScr["scr"].stringValue
I'm fetching data from a weather API. I'm not sure how to access the description?
"weather": <__NSSingleObjectArrayI 0x608000012910>(
{
description = "overcast clouds";
icon = 04n;
id = 804;
main = Clouds;
}
)
I tried:
print(weatherDict["weather"]!.description!)
It just gave me this:
(
{
description = "overcast clouds";
icon = 04n;
id = 804;
main = Clouds;
}
)
How do I properly access the description?
weather contains an array of dictionaries.
description is a key in the first item of the array.
The code unwraps weather safely and checks if the array is not empty:
if let weatherArray = weatherDict["weather"] as? [[String:Any]],
let weather = weatherArray.first {
print(weather["description"]) // the value is an optional.
}
I am parsing twiter search api json data with NSJSONSerialization.Requirement is to search tweets by hashtag.In Twitter api console tool I am correctly getting data about 15 tweets.
written code is
if let results: NSDictionary = NSJSONSerialization .JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments , error: errorPointer) as? NSDictionary {
}
I am getting results value as
{
"search_metadata" = {
"completed_in" = "0.05";
count = 15;
"max_id" = 680240431771156480;
"max_id_str" = 680240431771156480;
"next_results" = "?max_id=680240407322689535&q=%23ChristmasEve&include_entities=1";
query = "%23ChristmasEve";
"refresh_url" = "?since_id=680240431771156480&q=%23ChristmasEve&include_entities=1";
"since_id" = 0;
"since_id_str" = 0;
};
statuses = (
{
contributors = "<null>";
coordinates = "<null>";
"created_at" = "Fri Dec 25 04:15:31 +0000 2015";
entities = {
hashtags = (
{
indices = (
0,
13
);
text = ChristmasEve;
},
{
which is incomplete.
I even tried using SwiftyJSon library but I am getting similar results.
Is there any way to get statuses/Tweet info value without using any external library?
Given the fact that you mentioned you are getting multiple tweets (15), the JSON data you're getting back from the API possibly is an array, not a dictionary. It's a good practice to handle both cases when you make network calls:
do {
let object = try NSJSONSerialization.JSONObjectWithData(data, options: [])
if let dictionary = object as? [NSObject: AnyObject] {
// Handle dictionary
} else if let array = object as? [[NSObject: AnyObject]] {
// Handle array
}
} catch {
}
hi friend this is my JSON file apitest[18318:207] { ErrorCode = 900; ErrorMessage = ""; Result = ( { DeviceInfoId = 12; Email = "rocky#itg.com"; FirstName = Rocky; LastName = Yadav; ProfileImage = "<null>"; ThumbnailImage = "<null>"; UserId = 153; } ); TokenID = 59nUniliob; isError = 0; }
Can you please explain me how to parse the above JSON file and save the values in sqlite database this
You can use the SBJson parser to get a dictionary/array out of a json (depending on your response). You can then get the individual values from the dictionary/array and save them into your database.
The git repo also has some examples on how to use the parser.