0

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.

  • Related: https://stackoverflow.com/questions/28087688/alphabetical-sections-in-table-table-view-in-swift/53628028#53628028. The solution in the linked answer is outdated. And since Swift 3 (released 3 years ago) a JSON dictionary is `[String:Any]` not `[String:AnyObject]` and `mutableContainers` is pointless in Swift anyway. – vadian Oct 21 '19 at 17:12
  • 1
    Thanks vadian. I think the only bits of code I need to worry about are from the makeDataSource function that seems to be where the information for the section titles is coming from. Unless I'm completely wrong on that point. – Jackie Norstrom Oct 21 '19 at 17:38
  • Rob, no I could change it. That was just something I had been using that was working for me. If the getData() JSON structure is better, instead of the JSONParsing function I had been using, I don't mind using that. Or if there's even a better way to parse the JSON I don't mind using that either. Edit: I'm editing the original post to include my Signs Class code that I believe has some json parser/decode code in it. – Jackie Norstrom Oct 21 '19 at 18:28

0 Answers0