iOS/설명
[iOS] json파일 dictionary로 불러오기
Sky Titan
2022. 4. 22. 21:30
728x90
json파일 dictionary로 불러오기
- Bundle에서 해당 파일의 url을 불러온다.
- JSONSerialization에서 url을 이용해서 만든 Data 오브젝트에서 jsonObject를 생성하고 [String: Any] 타입으로 캐스팅한다.

if let url = Bundle.main.url(forResource: "Person", withExtension: "json") {
if let jsonDict = try? JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [String: Any] {
print(jsonDict["name"] ?? "")
print(jsonDict["age"] ?? 0)
}
}
/*
Park
20
*/
json파일을 객체로 Decoding하기
class Person: Decodable {
let name: String
let age: Int
let pet: Pet
}
class Pet: Decodable {
let name: String
let age: Int
let species: PetSpecies
}
enum PetSpecies: String, Decodable {
case cat
case dog
}
if let url = Bundle.main.url(forResource: "Person", withExtension: "json") {
if let person = try? JSONDecoder().decode(Person.self, from: Data(contentsOf: url)) {
print(person.name)
print(person.age)
print(person.pet.name)
print(person.pet.age)
print(person.pet.species)
}
}
/*
Park
20
Nabi
7
cat
*/
728x90