I've been using JSONParsing to display my data when you search for a term. Now I want to list out all of those terms in an alphabetized list. But am having trouble getting the code to work correctly. I've replicated some code from someone else that was having the same problem and got that to work but I'm having trouble implementing my own code.
I currently am parsing my JSON with this code:
func parseJSONSignDictionary() {
if let url = Bundle.main.url(forResource: "csvjson", withExtension: "json") {
do {
let date = Date()
let data = try Data(contentsOf: url)
if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Any] {
(json["results"] as? [[String:Any]])?.forEach { j in
if let name = j["identifier"] as? String, let id = j["id"] as? Int {
let sign = Signs(name: name, number: id)
signsArray.append(sign)
}
}
}
print("Took", Date().timeIntervalSince(date))
} catch {
print(error.localizedDescription)
}
}
}
Edit to add some more code, this is my Signs class, which would replace the Restaurant Array/Class:
class Signs: NSObject, Decodable, NSCoding {
private var _signName: String!
private var _signNumber: Int!
var signName: String {
return _signName
}
var signNumber: Int {
return _signNumber
}
func encode(with aCoder: NSCoder) {
aCoder.encode(signName, forKey: "signNameKey")
}
required init?(coder aDecoder: NSCoder) {
print("Trying to turn Data into Sign")
self._signName = aDecoder.decodeObject(forKey: "signNameKey") as? String
}
init(name: String, number: Int) {
self._signName = name
self._signNumber = number
}
}
The code from another StackOverflow that I'm trying to use is from here. question:Display data from JSON in alphabetical sections in Table View in Swift
func makeDataSource(names:[String:[AnyObject]]) {
var dict = [String:[Restaurant]]()
let letters = NSCharacterSet.letters
for (_,value) in names {
//Iterating Restaurants
for resObj in value {
if let restaurantName = resObj["name"] as? String {
let restaurant = Restaurant(name: restaurantName)
var key = String(describing: restaurant.name.first!)
//To check whether key is alphabet or not
key = isKeyCharacter(key: key, letters: letters) ? key : "#"
if let keyValue = dict[key] {
//Already value exists for that key
var filtered = keyValue
filtered.append(restaurant)
//Sorting of restaurant names alphabetically
//filtered = filtered.sorted(by: {$0.0.name < $0.1.name})
dict[key] = filtered
} else {
let filtered = [restaurant]
dict[key] = filtered
}
}
}
}
//To sort the key header values
self.dataArray = Array(dict).sorted(by: { $0.0 < $1.0 })
//Logic to just shift the # category to bottom
let temp = self.dataArray[0]
self.dataArray.removeFirst()
self.dataArray.append(temp)
self.indexTitles = Array(dict.keys.sorted(by: <))
let tempIndex = self.indexTitles[0]
self.indexTitles.removeFirst()
self.indexTitles.append(tempIndex)
}
I have my own array that would replace Restaurant, called Signs.
if let restaurantName = resObj["name"] as? String {
I'm also wondering where this "name" is being pulled from? Is it the array/model which has the var name?
I'm not sure since I have a way to access the JSON data with my own function if I even need to try to use the getdata() function.
I just wanna understand what I'm missing, and how to do it on my own to get the code to work properly.
I am properly loading up my own profile information in an iOS Swift application, but the JSON has an object associated with it which is confusing me on how to properly parse it in order to access the data within it. Here is my method.
func attemptToLoadProfile(hash: String) {
let url = "https://www.gravatar.com/\(hash).json"
let fileURL = URL(string: url)
do {
let contents = try String(contentsOf: fileURL!)
let data = contents.data(using: String.Encoding.utf8)
let json = try? JSONSerialization.jsonObject(with: data!, options: [])
print(json!)
} catch {
print("error parsing json")
}
}
This works fine, but when I print it out, the JSON is formatted like this.
{
entry = (
{
displayName = edolecki;
hash = <myhash here>;
id = 1333520;
name = {
familyName = Dolecki;
formatted = "Eric Dolecki";
givenName = Eric;
};
photos = (
{
type = thumbnail;
value = "https://secure.gravatar.com/avatar/<myhash here>";
}
);
preferredUsername = edolecki;
profileUrl = "http://gravatar.com/edolecki";
requestHash = <myhash here>;
thumbnailUrl = "https://secure.gravatar.com/avatar/<myhash here>";
urls = (
);
}
);
}
How do I parse the JSON seeing there is that entry object at the root? I am after displayName, id, etc. I normally parse JSON without a more simplified root. I haven't seen this before.
The value associated with the entry key is just an array with one element. In this case, you can access json["entry"], cast it to a [[String: Any]] and access the first element [0]. Then you can access the things you want, like displayName and id.
A better way to do this is use Codable. Using QuickType, I generated this code:
struct Root: Codable {
let entry: [Entry]
}
struct Entry: Codable {
let id, hash, requestHash: String
let profileURL: URL
let preferredUsername: String
let thumbnailURL: URL
let photos: [Photo]
let displayName: String
enum CodingKeys: String, CodingKey {
case id, hash, requestHash
case profileURL = "profileUrl"
case preferredUsername
case thumbnailURL = "thumbnailUrl"
case photos, displayName
}
}
struct Photo: Codable {
let value: URL
let type: String
}
Then you can do this to parse the json:
let decoder = JSONDecoder()
let root = try decoder.decode(Root.self, from: data)
// e.g.
let displayName = root.entry[0].displayName
If you don't need any of the json KVPs, just remove it from the struct.
I have this json output that I want to parse using Codable:
{
"success": true,
"total": 1,
"users": [
{
"user": {
"id": "1",
"fname": "admin",
"lname": "admin",
"login": "admin",
"actif": "0",
"last_connection_date": "2018-01-18 16:02:34"
}
}
],
"msg": ""
}
And I just want to exctact the user's informations out of it.
My user's model
import RealmSwift
class User: Object, Codable {
#objc dynamic var id: String = ""
#objc dynamic var fname: String = ""
#objc dynamic var lname: String = ""
#objc dynamic var login: String = ""
// private enum CodingKeys : String, CodingKey {
// case id = "users[0].user.id"
// case fname = "users[0].user.fname"
// case lname = "users[0].lname"
// case login = "users[0].user.login"
// case password = "users[0].user.password"
// }
}
// Somewhere in my code
Alamofire.request(Path.userInformations(id: userId).rawValue).
responseJSON(completionHandler: { response in
do {
let user = try JSONDecoder().decode(User.self, from: response.data!)
} catch (let error) {
print(error.localizedDescription)
}
})
I've tried extracting the user's object, but wasn't successful casting it to Data to feed it to JSONDecoder().decode() method.
Responding to Vishal16 's comment
I've tried you first approach. It does not seem to work because, I think, of keyword "user" before the user's object. I've tried adding a new struct that wrap the user's object, but does not solve it.
struct ResponseBody : Codable {
var success : Bool?
var total : Int?
var users : [UserHolder]?
var msg : String?
var query_start : String?
var query_end : String?
var query_time : String?
var paging : Bool?
}
struct UserHolder : Codable {
var user: User?
enum CodingKeys: String, CodingKey {
case user = "user"
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
user = try values.decodeIfPresent(User.self, forKey: .user)
}
}
I think your response class structure should be like:
import Foundation
struct ResponseBody : Codable {
var status : Bool?
var total : Int?
var users : [User]? //list of users
var msg : String?
enum CodingKeys: String, CodingKey {
case status = "status"
case total = "total"
case users = "users"
case msg = "msg"
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
status = try values.decodeIfPresent(Bool.self, forKey: . status)
total = try values.decodeIfPresent(Int.self, forKey: . total)
users = try values.decodeIfPresent([User].self, forKey: . users)
msg = try values.decodeIfPresent(String.self, forKey: . msg)
}
}
Now you will able to retrive your JSON data to object
let jsonDecoder = JSONDecoder()
let response = try jsonDecoder.decode(ResponseBody.self, from: data)
for user in response.users {
// user object is here
}
#edit
If you do not want to parse full response to JSON object
First convert Data to JSON Object using
let jsonResponse = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! Dictionary
Get users list string JSON then convert it to Data and after that data to User List object
if let responseBody = jsonResponse["users"] {
let dataBody = (responseBody as! String).data(using: .utf8)!
if let obj = Utils.convertToArray(data: dataBody) {
print(obj) // list of user obj
}
}
Hear is the method using in above implementation
class func convertToArray(data: Data) -> [AnyObject]? {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [AnyObject]
} catch {
Constants.print(items: error.localizedDescription)
}
return nil
}
Hope this help you. Happy codding :)
So hear is the working code for you
It's just working fine in my Playground. Please see below screenshots
1.
2.
3.
Decode json output to a model
Result:
class User: Object, Codable {
#objc dynamic var id: String = ""
#objc dynamic var fname: String = ""
#objc dynamic var lname: String = ""
#objc dynamic var login: String = ""
}
class Users: Object, Codable {
#objc dynamic var users: [User]
}
And for decoding
let user = try JSONDecoder().decode(Users.self, from: response.data!)
I think it should resolve the issue.
The other way is, you have to convert your response.data to Dictionary to dig down to user object.
I am using NSJSONSerialization in Swift 1.2 to parse some json that is returned from an API response.
var err: NSError?
let opts = NSJSONReadingOptions.AllowFragments
let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData!, options: opts, error: &err)
The parsed json is provided as AnyObject?. I would like to use this optional to initialize a class object which can be used as the model data in an application.
class Alerts {
let type: String
let date: String
let description: String
let expires: String
let message: String
init(json: AnyObject) {
if let
jsonDict = json as? [String: AnyObject],
alertsArray = jsonDict["alerts"] as? [AnyObject],
alertsDict = alertsArray[0] as? [String: AnyObject],
type = alertsDict["type"] as? String,
date = alertsDict["date"] as? String,
description = alertsDict["description"] as? String,
expires = alertsDict["expires"] as? String,
message = alertsDict["message"] as? String
{
self.type = type
self.date = date
self.description = description
self.expires = expires
self.message = message
}
else
{
self.type = "err"
self.date = "err"
self.description = "err"
self.expires = "err"
self.message = "err"
}
}
}
// example of creating a data model from the json
let alerts = Alerts(json: json!)
alerts.type
alerts.date
alerts.description
alerts.expires
alerts.message
Since NSJSONSerialization returns an optional, I have to check for the existence of each value type as I extract the json data. As you can see in the above code, I used the improved optional bindings from Swift 1.2 to clean up the init method. Without using third-party libraries, is there anything else I can do to the class model (enums, structs, type aliases) to make it more readable? Should I use a struct for the model data instead of a class? Would it be possible to create a custom type using an enum or struct to represent a json object?
So without using third party libraries, the if let trees are usually the best practice, which you have shown. To help you later down the road, maybe recreate your object hierarchy in JSON as a Struct model in Swift. Something like:
var json = JSON(JSONData.sharedjson.jsonRaw!)
var mongoIdTest = json["resultset"]["account"]["mongoId"].string
struct Root {
var timestamp: Int?
var resultset = ResultSet()
init() {
self.timestamp = json["timestamp"].int
println(json)
}
}
struct ResultSet {
var alert: String?
var account = Account()
var customer = Customer()
init() {
}
}
struct Account {
var mongoId: String?
init() {
mongoId = json["resultset"]["account"]["mongoId"].string
}
}
struct Locations {
}
struct Customer {
var account: String?
var address: String?
var id: String?
var loginId: String?
var mongoId: String?
var name: String?
var opco = Opco()
init() {
account = json["resultset"]["customer"]["account"].string
address = json["resultset"]["customer"]["address"].string
id = json["resultset"]["customer"]["id"].string
loginId = json["resultset"]["customer"]["loginId"].string
mongoId = json["resultset"]["customer"]["mongoId"].string
name = json["resultset"]["customer"]["name"].string
}
}
struct Opco {
var id: String?
var phone: String?
var cutOffTime: String?
var name: String?
var payerId: String?
init() {
id = json["resultset"]["customer"]["opco"]["id"].string
phone = json["resultset"]["customer"]["opco"]["phone"].string
cutOffTime = json["resultset"]["customer"]["opco"]["cutOffTime"].string
name = json["resultset"]["customer"]["opco"]["name"].string
payerId = json["resultset"]["customer"]["opco"]["payerId"].string
}
}
This way you can still use autocomplete and dot notation to navigate through your hierarchy.
Edit: I have a data structure from an actual project I've worked on added to the answer, hopefully this gives a better idea. Keep in mind that I'm using SwiftyJSON for the JSON() call.
Edit 2:
This is a method I found for getting JSON info into a Swift dictionary without the use of some other library. I'm not sure there is another way to do it that's easier without the use of third party libraries.
var urlToRequest = "https://EXAMPLE.com/api/account.login?username=MY_USERNAME&password=Hunter2"
if let json = NSData(contentsOfURL: NSURL(string: urlToRequest)!) {
// Parse JSON to Dictionary
var error: NSError?
let boardsDictionary = NSJSONSerialization.JSONObjectWithData(json, options: NSJSONReadingOptions.MutableContainers, error: &error) as? Dictionary<String, AnyObject>
fulljson = boardsDictionary
// Display all keys and values
println("Keys in User Data:")
for (key, value) in boardsDictionary! {
println("\(key)-------\(value)")
}
println(fulljson?["resultset"])
}
else {
println("Test JSON nil: No Connection?")
}
That dictionary will be the input for your Structs.
Is there a way to properly deserialize a JSON response to Swift objects resp. using DTOs as containers for fixed JSON APIs?
Something similar to http://james.newtonking.com/json or something like this example from Java
User user = jsonResponse.readEntity(User.class);
whereby jsonResponse.toString() is something like
{
"name": "myUser",
"email": "user#example.com",
"password": "passwordHash"
}
SWIFT 4 Update
Since you give a very simple JSON object the code prepared for to handle that model. If you need more complicated JSON models you need to improve this sample.
Your Custom Object
class Person : NSObject {
var name : String = ""
var email : String = ""
var password : String = ""
init(JSONString: String) {
super.init()
var error : NSError?
let JSONData = JSONString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
let JSONDictionary: Dictionary = NSJSONSerialization.JSONObjectWithData(JSONData, options: nil, error: &error) as NSDictionary
// Loop
for (key, value) in JSONDictionary {
let keyName = key as String
let keyValue: String = value as String
// If property exists
if (self.respondsToSelector(NSSelectorFromString(keyName))) {
self.setValue(keyValue, forKey: keyName)
}
}
// Or you can do it with using
// self.setValuesForKeysWithDictionary(JSONDictionary)
// instead of loop method above
}
}
And this is how you invoke your custom class with JSON string.
override func viewDidLoad() {
super.viewDidLoad()
let jsonString = "{ \"name\":\"myUser\", \"email\":\"user#example.com\", \"password\":\"passwordHash\" }"
var aPerson : Person = Person(JSONString: jsonString)
println(aPerson.name) // Output is "myUser"
}
I recommend that you use code generation (http://www.json4swift.com) to create native models out of the json response, this will save your time of parsing by hand and reduce the risk of errors due to mistaken keys, all elements will be accessible by model properties, this will be purely native and the models will make more sense rather checking the keys.
Your conversion will be as simple as:
let userObject = UserClass(userDictionary)
print(userObject!.name)
Swift 2: I really like the previous post of Mohacs! To make it more object oriented, i wrote a matching Extension:
extension NSObject{
convenience init(jsonStr:String) {
self.init()
if let jsonData = jsonStr.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
{
do {
let json = try NSJSONSerialization.JSONObjectWithData(jsonData, options: []) as! [String: AnyObject]
// Loop
for (key, value) in json {
let keyName = key as String
let keyValue: String = value as! String
// If property exists
if (self.respondsToSelector(NSSelectorFromString(keyName))) {
self.setValue(keyValue, forKey: keyName)
}
}
} catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
}
}
else
{
print("json is of wrong format!")
}
}
}
custom classes:
class Person : NSObject {
var name : String?
var email : String?
var password : String?
}
class Address : NSObject {
var city : String?
var zip : String?
}
invoking custom classes with JSON string:
var jsonString = "{ \"name\":\"myUser\", \"email\":\"user#example.com\", \"password\":\"passwordHash\" }"
let aPerson = Person(jsonStr: jsonString)
print(aPerson.name!) // Output is "myUser"
jsonString = "{ \"city\":\"Berlin\", \"zip\":\"12345\" }"
let aAddress = Address(jsonStr: jsonString)
print(aAddress.city!) // Output is "Berlin"
Yet another JSON handler I wrote:
https://github.com/dankogai/swift-json
With it you can go like this:
let obj:[String:AnyObject] = [
"array": [JSON.null, false, 0, "", [], [:]],
"object":[
"null": JSON.null,
"bool": true,
"int": 42,
"double": 3.141592653589793,
"string": "a α\t弾\n𪚲",
"array": [],
"object": [:]
],
"url":"http://blog.livedoor.com/dankogai/"
]
let json = JSON(obj)
json.toString()
json["object"]["null"].asNull // NSNull()
json["object"]["bool"].asBool // true
json["object"]["int"].asInt // 42
json["object"]["double"].asDouble // 3.141592653589793
json["object"]["string"].asString // "a α\t弾\n𪚲"
json["array"][0].asNull // NSNull()
json["array"][1].asBool // false
json["array"][2].asInt // 0
json["array"][3].asString // ""
As you see no !? needed between subscripts.
In addition to that you can apply your own schema like this:
//// schema by subclassing
class MyJSON : JSON {
override init(_ obj:AnyObject){ super.init(obj) }
override init(_ json:JSON) { super.init(json) }
var null :NSNull? { return self["null"].asNull }
var bool :Bool? { return self["bool"].asBool }
var int :Int? { return self["int"].asInt }
var double:Double? { return self["double"].asDouble }
var string:String? { return self["string"].asString }
var url: String? { return self["url"].asString }
var array :MyJSON { return MyJSON(self["array"]) }
var object:MyJSON { return MyJSON(self["object"]) }
}
let myjson = MyJSON(obj)
myjson.object.null // NSNull?
myjson.object.bool // Bool?
myjson.object.int // Int?
myjson.object.double // Double?
myjson.object.string // String?
myjson.url // String?
There's a great example by Apple for deserializing JSON with Swift 2.0
The trick is to use the guard keyword and chain the assignments like so:
init?(attributes: [String : AnyObject]) {
guard let name = attributes["name"] as? String,
let coordinates = attributes["coordinates"] as? [String: Double],
let latitude = coordinates["lat"],
let longitude = coordinates["lng"],
else {
return nil
}
self.name = name
self.coordinates = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
}
I personally prefer native parsing vs any 3rd party, as it is transparent and magic-less. (and bug less?)
Using quicktype, I generated your model and serialization helpers from your sample:
import Foundation
struct User: Codable {
let name: String
let email: String
let password: String
}
extension User {
static func from(json: String, using encoding: String.Encoding = .utf8) -> OtherUser? {
guard let data = json.data(using: encoding) else { return nil }
return OtherUser.from(data: data)
}
static func from(data: Data) -> OtherUser? {
let decoder = JSONDecoder()
return try? decoder.decode(OtherUser.self, from: data)
}
var jsonData: Data? {
let encoder = JSONEncoder()
return try? encoder.encode(self)
}
var jsonString: String? {
guard let data = self.jsonData else { return nil }
return String(data: data, encoding: .utf8)
}
}
Then parse User values like this:
let user = User.from(json: """{
"name": "myUser",
"email": "user#example.com",
"password": "passwordHash"
}""")!
I wrote this small open-source library recently that lets you quickly and easily deserialize dictionaries into Swift objects: https://github.com/isair/JSONHelper
Using it, deserializing data becomes as easy as this:
var myInstance = MyClass(data: jsonDictionary)
or
myInstance <-- jsonDictionary
And models need to look only like this:
struct SomeObjectType: Deserializable {
var someProperty: Int?
var someOtherProperty: AnotherObjectType?
var yetAnotherProperty: [YetAnotherObjectType]?
init(data: [String: AnyObject]) {
someProperty <-- data["some_key"]
someOtherProperty <-- data["some_other_key"]
yetAnotherProperty <-- data["yet_another_key"]
}
}
Which, in your case, would be:
struct Person: Deserializable {
var name: String?
var email: String?
var password: String?
init(data: [String: AnyObject]) {
name <-- data["name"]
email <-- data["email"]
password <-- data["password"]
}
}
If you would like parse from and to json without the need to manually map keys and fields, then you could also use EVReflection. You can then use code like:
var user:User = User(json:jsonString)
or
var jsonString:String = user.toJsonString()
The only thing you need to do is to use EVObject as your data objects base class.
See the GitHub page for more detailed sample code
I am expanding upon Mohacs and Peter Kreinz's excellent answers just a bit to cover the array of like objects case where each object contains a mixture of valid JSON data types. If the JSON data one is parsing is an array of like objects containing a mixture of JSON data types, the do loop for parsing the JSON data becomes this.
// Array of parsed objects
var parsedObjects = [ParsedObject]()
do {
let json = try NSJSONSerialization.JSONObjectWithData(jsonData, options: []) as [Dictionary<String, AnyObject>]
// Loop through objects
for dict in json {
// ParsedObject is a single instance of an object inside the JSON data
// Its properties are a mixture of String, Int, Double and Bool
let parsedObject = ParsedObject()
// Loop through key/values in object parsed from JSON
for (key, value) in json {
// If property exists, set the value
if (parsedObject.respondsToSelector(NSSelectorFromString(keyName))) {
// setValue can handle AnyObject when assigning property value
parsedObject.setValue(keyValue, forKey: keyName)
}
}
parsedObjects.append(parsedObject)
}
} catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
}
This way lets you get the user from a URL. It's parse the NSData to a NSDictionary and then to your NSObject.
let urlS = "http://api.localhost:3000/"
func getUser(username: Strung) -> User {
var user = User()
let url = NSURL(string: "\(urlS)\(username)")
if let data = NSData(contentsOfURL: url!) {
setKeysAndValues(user, dictionary: parseData(data))
}
return user
}
func setKeysAndValues (object : AnyObject, dictionary : NSDictionary) -> AnyObject {
for (key, value) in dictionary {
if let key = key as? String, let value = value as? String {
if (object.respondsToSelector(NSSelectorFromString(key))) {
object.setValue(value, forKey: key)
}
}
}
return object
}
func parseData (data : NSData) -> NSDictionary {
var error: NSError?
return NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as! NSDictionary
}
In Swift 4, You can use the Decoding, CodingKey protocols to deserialize the JSON response:
Create the class which confirm the decodable protocol
class UserInfo: Decodable
Create members of the class
var name: String
var email: String
var password: String
Create JSON key enum which inherits from CodingKey
enum UserInfoCodingKey: String, CodingKey {
case name
case password
case emailId
}
Implement init
required init(from decoder: Decoder) throws
The whole class look like :
Call Decoder
// jsonData is JSON response and we get the userInfo object
let userInfo = try JsonDecoder().decode(UserInfo.self, from: jsonData)
You do this by using NSJSONSerialization. Where data is your JSON.
First wrap it in an if statement to provide some error handling capablity
if let data = data,
json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String: AnyObject] {
// Do stuff
} else {
// Do stuff
print("No Data :/")
}
then assign them:
let email = json["email"] as? String
let name = json["name"] as? String
let password = json["password"] as? String
Now, This will show you the result:
print("Found User iname: \(name) with email: \(email) and pass \(password)")
Taken from this Swift Parse JSON tutorial. You should check out the tutorial as it goes a lot more in depth and covers better error handling.