'How to get specific element from array of type any in swift?
JSON file:
[
{
"name" : "Tom Harrys",
"email" : "[email protected]",
"password" : "tomharry123"
},
{
"name" : "Sam Billing",
"email" : "[email protected]",
"password" : "sambillings789"
},
{
"name" : "Adam Gosh",
"email" : "[email protected]",
"password" : "adamghosy989"
}
]
UTIL file:
class Utils {
static func loadData(filename : String) -> [Any] {
let filePath = Bundle(for: self).path(forResource: filename, ofType: "json") ?? "default"
let url = URL(fileURLWithPath: filePath)
do {
let data = try Data(contentsOf: url)
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
let exampleArray = json as! [Any]
if exampleArray.isEmpty {
XCTFail("Source file \(filename) is empty.")
}
return exampleArray
}
catch {
XCTFail("Error: \(error)")
XCTFail("File \(filename) not found.")
return []
}
}
}
Test file:
func loginAccount() {
let dataSource = Utils.loadData(filename: "example")
dataSource.contains(where: { ($0.name == "Sam Billing"})
}
In this code dataSource got 3 value same as Json file. Now I want to fill the sign up form with specific value
( "name" : "Sam Billing", "email" : "[email protected]", "password" : "sambillings789" )
from the array.
Solution 1:[1]
You should not be using JSONSerializer in Swift. A better option is a JSONDecoder. JSONDecoder will allow you to establish and preserve the type information for the data you've decoded. Here is an Playground example of how you would use JSONDecoder to handle this data set, then one technique extract Sam's record from the array of users.
import UIKit
import Foundation
let JSONContent = """
[
{
"name" : "Tom Harrys",
"email" : "[email protected]",
"password" : "tomharry123"
},
{
"name" : "Sam Billing",
"email" : "[email protected]",
"password" : "sambillings789"
},
{
"name" : "Adam Gosh",
"email" : "[email protected]",
"password" : "adamghosy989"
}
]
""".data(using: .utf8)!
struct UserRecord : Decodable {
let name : String
let email: String
let password: String // Don't pass passwords in plain text around in JSON
}
class Utils {
static func loadData() -> [UserRecord] {
do {
let decoder = JSONDecoder()
let data = JSONContent
let json = try decoder.decode([UserRecord].self, from: data)
return json
}
catch let error {
print("The json could not be decoded \(error)")
return []
}
}
}
let users = Utils.loadData()
if let sam = users.first(where: { user in user.email.caseInsensitiveCompare("[email protected]") == .orderedSame }) {
debugPrint(sam)
} else {
print("Sam was missing")
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
