Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 592 Vote(s) - 3.55 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Reading in a JSON File Using Swift

#11
**Xcode 8 Swift 3** read json from file update:

if let path = Bundle.main.path(forResource: "userDatabseFakeData", ofType: "json") {
do {
let jsonData = try NSData(contentsOfFile: path, options: NSData.ReadingOptions.mappedIfSafe)
do {
let jsonResult: NSDictionary = try JSONSerialization.jsonObject(with: jsonData as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
if let people : [NSDictionary] = jsonResult["person"] as? [NSDictionary] {
for person: NSDictionary in people {
for (name,value) in person {
print("\(name) , \(value)")
}
}
}
} catch {}
} catch {}
}
Reply

#12
**Latest swift 3.0 absolutely working**


func loadJson(filename fileName: String) -> [String: AnyObject]?
{
if let url = Bundle.main.url(forResource: fileName, withExtension: "json")
{
if let data = NSData(contentsOf: url) {
do {
let object = try JSONSerialization.jsonObject(with: data as Data, options: .allowFragments)
if let dictionary = object as? [String: AnyObject] {
return dictionary
}
} catch {
print("Error!! Unable to parse \(fileName).json")
}
}
print("Error!! Unable to load \(fileName).json")
}
return nil
}
Reply

#13
SWIFTYJSON VERSION SWIFT 3

func loadJson(fileName: String) -> JSON {

var dataPath:JSON!

if let path : String = Bundle.main.path(forResource: fileName, ofType: "json") {
if let data = NSData(contentsOfFile: path) {
dataPath = JSON(data: data as Data)
}
}
return dataPath
}
Reply

#14
fileprivate class BundleTargetingClass {}
func loadJSON<T>(name: String) -> T? {
guard let filePath = Bundle(for: BundleTargetingClass.self).url(forResource: name, withExtension: "json") else {
return nil
}

guard let jsonData = try? Data(contentsOf: filePath, options: .mappedIfSafe) else {
return nil
}

guard let json = try? JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) else {
return nil
}

return json as? T
}

👆🏻 copy-paste ready, 3rd party framework independent solution.

usage 👇🏻

`let json:[[String : AnyObject]] = loadJSON(name: "Stations")!`
Reply

#15
**Updated for Swift 3** with safest way

private func readLocalJsonFile() {

if let urlPath = Bundle.main.url(forResource: "test", withExtension: "json") {

do {
let jsonData = try Data(contentsOf: urlPath, options: .mappedIfSafe)

if let jsonDict = try JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) as? [String: AnyObject] {

if let personArray = jsonDict["person"] as? [[String: AnyObject]] {

for personDict in personArray {

for (key, value) in personDict {

print(key, value)
}
print("\n")
}
}
}
}

catch let jsonError {
print(jsonError)
}
}
}


[![enter image description here][1]][1]


[1]:
Reply

#16
This worked for me with XCode 8.3.3

func fetchPersons(){

if let pathURL = Bundle.main.url(forResource: "Person", withExtension: "json"){

do {

let jsonData = try Data(contentsOf: pathURL, options: .mappedIfSafe)

let jsonResult = try JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) as! [String: Any]
if let persons = jsonResult["person"] as? [Any]{

print(persons)
}

}catch(let error){
print (error.localizedDescription)
}
}
}
Reply

#17
If anyone is looking for [SwiftyJSON][1] Answer:<br>
**Update:**<br>
For `Swift 3/4`:

if let path = Bundle.main.path(forResource: "assets/test", ofType: "json") {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .alwaysMapped)
let jsonObj = try JSON(data: data)
print("jsonData:\(jsonObj)")
} catch let error {
print("parse error: \(error.localizedDescription)")
}
} else {
print("Invalid filename/path.")
}



[1]:

[To see links please register here]

[2]:

[To see links please register here]

Reply

#18

Follow the below code :

if let path = NSBundle.mainBundle().pathForResource("test", ofType: "json")
{
if let jsonData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)
{
if let jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: nil) as? NSDictionary
{
if let persons : NSArray = jsonResult["person"] as? NSArray
{
// Do stuff
}
}
}
}

The array "persons" will contain all data for key person. Iterate throughs to fetch it.

### Swift 4.0:

if let path = Bundle.main.path(forResource: "test", ofType: "json") {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
if let jsonResult = jsonResult as? Dictionary<String, AnyObject>, let person = jsonResult["person"] as? [Any] {
// do stuff
}
} catch {
// handle error
}
}
Reply

#19

## Swift 4.1 Updated Xcode 9.2 ##

if let filePath = Bundle.main.path(forResource: "fileName", ofType: "json"), let data = NSData(contentsOfFile: filePath) {

do {
let json = try JSONSerialization.jsonObject(with: data as Data, options: JSONSerialization.ReadingOptions.allowFragments)
}
catch {
//Handle error
}
}
Reply

#20
First create a Struc codable like this:

struct JuzgadosList : Codable {
var CP : Int
var TEL : String
var LOCAL : String
var ORGANO : String
var DIR : String
}

Now declare the variable

var jzdosList = [JuzgadosList]()

Read from main directory

func getJsonFromDirectory() {

if let path = Bundle.main.path(forResource: "juzgados", ofType: "json") {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .alwaysMapped)
let jList = try JSONDecoder().decode([JuzgadosList].self, from: data)
self.jzdosList = jList

DispatchQueue.main.async() { () -> Void in
self.tableView.reloadData()
}

} catch let error {
print("parse error: \(error.localizedDescription)")
}
} else {
print("Invalid filename/path.")
}
}

Read from web

func getJsonFromUrl(){

self.jzdosList.removeAll(keepingCapacity: false)

print("Internet Connection Available!")

guard let url = URL(string: "yourURL") else { return }

let request = URLRequest(url: url, cachePolicy: URLRequest.CachePolicy.reloadIgnoringLocalCacheData, timeoutInterval: 60.0)
URLSession.shared.dataTask(with: request) { (data, response, err) in
guard let data = data else { return }
do {
let jList = try JSONDecoder().decode([JuzgadosList].self, from: data)
self.jzdosList = jList

DispatchQueue.main.async() { () -> Void in
self.tableView.reloadData()
}
} catch let jsonErr {
print("Error serializing json:", jsonErr)
}
}.resume()
}
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through