JSON 파일이 있고 테이블보기에서 개체 목록을 구문 분석하고 사용하고 싶습니다. 누구든지 신속하게 JSON 파일을 구문 분석하는 코드를 공유 할 수 있습니다.
JSON 파일이 있고 테이블보기에서 개체 목록을 구문 분석하고 사용하고 싶습니다. 누구든지 신속하게 JSON 파일을 구문 분석하는 코드를 공유 할 수 있습니다.
답변:
더 간단 할 수 없습니다.
import Foundation
let jsonData: Data = /* get your json data */
let jsonDict = try JSONSerialization.jsonObject(with: jsonData) as? NSDictionary
즉, Swift 4에 도입 된 Codable API를 사용하는 것이 좋습니다 .
let jsonData = NSData.dataWithContentsOfFile(filepath, options: .DataReadingMappedIfSafe, error: nil)
NSData(contentsOfFile: path). 참조 developer.apple.com/library/ios/documentation/Cocoa/Reference/... :
API 요청 만들기
var request: NSURLRequest = NSURLRequest(URL: url)
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)
응답 준비
아래와 같이 배열 선언
var data: NSMutableData = NSMutableData()
응답 받기
1.
func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
// Received a new request, clear out the data object
self.data = NSMutableData()
}
2.
func connection(connection: NSURLConnection!, didReceiveData data: NSData!) {
// Append the received chunk of data to our data object
self.data.appendData(data)
}
삼.
func connectionDidFinishLoading(connection: NSURLConnection!) {
// Request complete, self.data should now hold the resulting info
// Convert the retrieved data in to an object through JSON deserialization
var err: NSError
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
if jsonResult.count>0 && jsonResult["results"].count>0 {
var results: NSArray = jsonResult["results"] as NSArray
self.tableData = results
self.appsTableView.reloadData()
}
}
때 NSURLConnection응답을 수신, 우리가 기대할 수있는 didReceiveResponse방법은 우리를 대신하여 호출 할 수 있습니다. 이 시점에서 우리는 단순히 self.data = NSMutableData()새로운 빈 데이터 객체를 생성하여 데이터를 재설정 합니다.
연결이 완료되면 메소드에서 데이터 수신을 시작합니다 didReceiveData. 여기에 전달되는 데이터 인수는 모든 육즙 정보의 출처입니다. 들어오는 각 청크를 유지해야하므로 이전에 지운 self.data 개체에 추가합니다.
마지막으로 연결이 완료되고 모든 데이터가 수신되면를 connectionDidFinishLoading호출하고 앱에서 데이터를 사용할 준비가 된 것입니다. 만세!
여기서 connectionDidFinishLoading메서드는 Url의 결과를 역 직렬화하여 NSJSONSerialization원시 데이터를 유용한 Dictionary개체 로 변환 하는 클래스를 사용합니다 .
방금 JSON이라는 클래스를 작성하여 Swift에서 JSON을 ES5의 JSON 개체처럼 쉽게 처리 할 수 있습니다.
다음과 같이 신속한 객체를 JSON으로 변환하십시오.
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()
... 또는 문자열 ...
let json = JSON.parse("{\"array\":[...}")
... 또는 URL.
let json = JSON.fromURL("http://api.dan.co.jp/jsonenv")
Tree Traversal
아래 첨자를 통해 요소를 탐색하면됩니다.
json["object"]["null"].asNull // NSNull()
// ...
json["object"]["string"].asString // "a α\t弾\n𪚲"
json["array"][0].asNull // NSNull()
json["array"][1].asBool // false
// ...
SwiftyJSON 과 마찬가지로 첨자 항목이 존재하지 않아도 걱정할 필요가 없습니다.
if let b = json["noexistent"][1234567890]["entry"].asBool {
// ....
} else {
let e = json["noexistent"][1234567890]["entry"].asError
println(e)
}
아래 첨자에 지쳤다면 다음과 같이 구성표를 추가하십시오.
//// schema by subclassing
class MyJSON : JSON {
init(_ obj:AnyObject){ super.init(obj) }
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 }
}
그리고 당신은 간다 :
let myjson = MyJSON(obj)
myjson.object.null
myjson.object.bool
myjson.object.int
myjson.object.double
myjson.object.string
// ...
네가 좋아하길 바래.
새로운 xCode 7.3+에서는 도메인을 예외 목록에 추가하는 것이 중요합니다 ( 내 info.plist 파일에 NSAppTransportSecurity를 어떻게 추가 할 수 있습니까? ). 지침은이 게시물을 참조하십시오. 그렇지 않으면 전송 기관 오류가 발생합니다.
다음은 Swift 2.0에서 JSON과 NSData를 변환하는 코드입니다.
// Convert from NSData to json object
func nsdataToJSON(data: NSData) -> AnyObject? {
do {
return try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers)
} catch let myJSONError {
print(myJSONError)
}
return nil
}
// Convert from JSON to nsdata
func jsonToNSData(json: AnyObject) -> NSData?{
do {
return try NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions.PrettyPrinted)
} catch let myJSONError {
print(myJSONError)
}
return nil;
}
스위프트 년 4 + 강력하게 사용하는 것이 좋습니다 Codable대신 JSONSerialization.
여기 Codable에는 Decodable및 Encodable. 이 Decodable프로토콜을 사용하면 DataJSON 형식으로이 프로토콜을 준수하는 사용자 지정 구조체 / 클래스 로 디코딩 할 수 있습니다 .
예를 들어 다음과 같은 간단한 상황을 상상해보십시오 Data(두 개체의 배열).
let data = Data("""
[
{"name":"Steve","age":56},
{"name":"iPhone","age":11}
]
""".utf8)
그런 다음 struct프로토콜 을 따르고 구현하십시오.Decodable
struct Person: Decodable {
let name: String
let age: Int
}
이제 첫 번째 매개 변수가 유형을 준수 하고이 유형을 디코딩 해야하는 사용 Data배열 로 디코딩 할 수 있습니다.PersonJSONDecoderDecodableData
do {
let people = try JSONDecoder().decode([Person].self, from: data)
} catch { print(error) }
... try예를 들어 이름 지정에 약간의 실수를하여 모델을 올바르게 디코딩 할 수 없기 때문에 디코딩 은 키워드 로 표시 되어야합니다.
json의 키가 속성 이름과 다른 경우 :
키에 snake_case을 사용하여 명명 된 경우의 디코더 설정할 수 있습니다 keyDecodingStrategy에 convertFromSnakeCase에서 키를 변경하는 property_name낙타 표기법에propertyName
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let people = try decoder.decode([Person].self, from: data)
고유 한 이름이 필요한 경우 키 이름을 선언하는 구조체 / 클래스 내에서 코딩 키를 사용할 수 있습니다.
let data = Data("""
{ "userName":"Codable", "age": 1 }
""".utf8)
struct Person: Decodable {
let name: String
let age: Int
enum CodingKeys: String, CodingKey {
case name = "userName"
case age
}
}
또한 json 응답을 객체 구조로 매핑하는 데 특화된 작은 라이브러리를 작성했습니다. 내부적으로 David Owens의 json-swift 라이브러리를 사용하고 있습니다. 다른 사람에게 유용 할 수도 있습니다.
https://github.com/prine/ROJSONParser
Employees.json 예
{
"employees": [
{
"firstName": "John",
"lastName": "Doe",
"age": 26
},
{
"firstName": "Anna",
"lastName": "Smith",
"age": 30
},
{
"firstName": "Peter",
"lastName": "Jones",
"age": 45
}]
}
다음 단계로 데이터 모델 (EmplyoeeContainer 및 Employee)을 생성해야합니다.
Employee.swift
class Employee : ROJSONObject {
required init() {
super.init();
}
required init(jsonData:AnyObject) {
super.init(jsonData: jsonData)
}
var firstname:String {
return Value<String>.get(self, key: "firstName")
}
var lastname:String {
return Value<String>.get(self, key: "lastName")
}
var age:Int {
return Value<Int>.get(self, key: "age")
}
}
EmployeeContainer.swift
class EmployeeContainer : ROJSONObject {
required init() {
super.init();
}
required init(jsonData:AnyObject) {
super.init(jsonData: jsonData)
}
lazy var employees:[Employee] = {
return Value<[Employee]>.getArray(self, key: "employees") as [Employee]
}()
}
그런 다음 실제로 JSON 응답의 객체를 매핑하려면 생성자의 매개 변수로 EmployeeContainer 클래스에 데이터를 전달하기 만하면됩니다. 데이터 모델을 자동으로 생성합니다.
var baseWebservice:BaseWebservice = BaseWebservice();
var urlToJSON = "http://prine.ch/employees.json"
var callbackJSON = {(status:Int, employeeContainer:EmployeeContainer) -> () in
for employee in employeeContainer.employees {
println("Firstname: \(employee.firstname) Lastname: \(employee.lastname) age: \(employee.age)")
}
}
baseWebservice.get(urlToJSON, callback:callbackJSON)
콘솔 출력은 다음과 같습니다.
Firstname: John Lastname: Doe age: 26
Firstname: Anna Lastname: Smith age: 30
Firstname: Peter Lastname: Jones age: 45
아주 간단하고 읽기 쉽습니다!
"mrap"에서 nicknames이 JSON 응답에서 문자열로{
"other": {
"nicknames": ["mrap", "Mikee"]
}
json 데이터를 NSData그대로 사용하므로 사전 처리 할 필요가 없습니다.
let parser = JSONParser(jsonData)
if let handle = parser.getString("other.nicknames[0]") {
// that's it!
}
면책 조항 : 나는 이것을 만들었고 그것이 모두에게 도움이되기를 바랍니다. 자유롭게 개선하십시오!
Swift에서 JSON을 구문 분석하는 것은 코드 생성을위한 훌륭한 작업입니다. http://www.guideluxe.com/JsonToSwift 에서 도구를 만들었습니다 .이를 위해 에서 .
클래스 이름과 함께 샘플 JSON 객체를 제공하면 도구가 해당 Swift 클래스와 필요한 보조 Swift 클래스를 생성하여 샘플 JSON이 암시하는 구조를 나타냅니다. 또한 NSJSONSerialization.JSONObjectWithData 메서드를 사용하는 메서드를 포함하여 Swift 개체를 채우는 데 사용되는 클래스 메서드도 포함됩니다. NSArray 및 NSDictionary 개체에서 필요한 매핑이 제공됩니다.
생성 된 코드에서 도구에 제공된 샘플과 일치하는 JSON이 포함 된 NSData 객체 만 제공하면됩니다.
재단 외에는 종속성이 없습니다.
내 작업은 http://json2csharp.com/ 에서 영감을 얻었습니다. 에서 .NET 프로젝트에 매우 편리합니다.
JSON 파일에서 NSData 객체를 만드는 방법은 다음과 같습니다.
let fileUrl: NSURL = NSBundle.mainBundle().URLForResource("JsonFile", withExtension: "json")!
let jsonData: NSData = NSData(contentsOfURL: fileUrl)!
참고 : 이것을 찾고 있다면 설치 방법을 모를 가능성이 높습니다 swifty. 여기 의 지침을 따르십시오 .
sudo gem install cocoapods
cd ~/Path/To/Folder/Containing/ShowTracker
다음으로 다음 명령을 입력하십시오.
pod init
그러면 Podfile프로젝트 의 기본값이 생성됩니다 . 는 Podfile당신이이 프로젝트에 의존하는 종속성 정의하는 곳입니다.
다음 명령을 입력 Podfile하여 Xcode편집 용 으로 엽니 다 .
open -a Xcode Podfile
Swiftypodfile에 추가
platform :ios, '8.0'
use_frameworks!
target 'MyApp' do
pod 'SwiftyJSON', '~> X.X.X'
end
var mURL = NSURL(string: "http://api.openweathermap.org/data/2.5/weather?q=London,uk&units=metric")
if mURL == nil{
println("You are stupid")
return
}
var request = NSURLRequest(URL: mURL!)
NSURLConnection.sendAsynchronousRequest(
request,
queue: NSOperationQueue.mainQueue(),
completionHandler:{ (
response: NSURLResponse!,
data: NSData!,
error: NSError!) -> Void in
if data != nil {
var mJSON = JSON(data: data!)
if let current_conditions = mJSON["weather"][0]["description"].string {
println("Current conditions: " + current_conditions)
} else {
println("MORON!")
}
if let current_temperature = mJSON["main"]["temp"].double {
println("Temperature: "+ String(format:"%.f", current_temperature) + "°C"
} else {
println("MORON!")
}
}
})
json parsig의 두 가지 방법을 사용하여 데이터를 수집 뷰로 표시하는 전체 뷰 컨트롤러
@IBOutlet weak var imagecollectionview: UICollectionView!
lazy var data = NSMutableData()
var dictdata : NSMutableDictionary = NSMutableDictionary()
override func viewDidLoad() {
super.viewDidLoad()
startConnection()
startNewConnection()
// Do any additional setup after loading the view, typically from a nib.
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dictdata.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CustomcellCollectionViewCell", forIndexPath: indexPath) as! CustomcellCollectionViewCell
cell.name.text = dictdata.valueForKey("Data")?.valueForKey("location") as? String
let url = NSURL(string: (dictdata.valueForKey("Data")?.valueForKey("avatar_url") as? String)! )
LazyImage.showForImageView(cell.image, url:"URL
return cell
}
func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let kWhateverHeightYouWant = 100
return CGSizeMake(self.view.bounds.size.width/2, CGFloat(kWhateverHeightYouWant))
}
func startNewConnection()
{
let url: URL = URL(string: "YOUR URL" as String)!
let session = URLSession.shared
let request = NSMutableURLRequest(url: url as URL)
request.httpMethod = "GET" //set the get or post according to your request
// request.cachePolicy = NSURLRequest.CachePolicy.ReloadIgnoringCacheData
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
let task = session.dataTask(with: request as URLRequest) {
( data, response, error) in
guard let _:NSData = data as NSData?, let _:URLResponse = response, error == nil else {
print("error")
return
}
let jsonString = NSString(data: data!, encoding:String.Encoding.utf8.rawValue) as! String
}
task.resume()
}
func startConnection(){
let urlPath: String = "your URL"
let url: NSURL = NSURL(string: urlPath)!
var request: NSURLRequest = NSURLRequest(URL: url)
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)!
connection.start()
}
func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
self.data.appendData(data)
}
func buttonAction(sender: UIButton!){
startConnection()
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
do {
let JSON = try NSJSONSerialization.JSONObjectWithData(self.data, options:NSJSONReadingOptions(rawValue: 0))
guard let JSONDictionary :NSDictionary = JSON as? NSDictionary else {
print("Not a Dictionary")
// put in function
return
}
print("JSONDictionary! \(JSONDictionary)")
dictdata.setObject(JSONDictionary, forKey: "Data")
imagecollectionview.reloadData()
}
catch let JSONError as NSError {
print("\(JSONError)")
} }
if let path = Bundle(for: BPPView.self).path(forResource: jsonFileName, ofType: "json") {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: NSData.ReadingOptions.mappedIfSafe)
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
self.levels = Mapper<Level>().mapArray(JSONArray: (json as! [[String : Any]]))!
print(levels.count)
} catch let error as NSError {
print(error.localizedDescription)
}
} else {
print("Invalid filename/path.")
}
파싱 할 적절한 : Mappable 객체 세트를 준비하기 전에
import UIKit
import ObjectMapper
class Level: Mappable {
var levelName = ""
var levelItems = [LevelItem]()
required init?(map: Map) {
}
// Mappable
func mapping(map: Map) {
levelName <- map["levelName"]
levelItems <- map["levelItems"]
}
import UIKit
import ObjectMapper
class LevelItem: Mappable {
var frontBackSide = BPPFrontBack.Undefined
var fullImageName = ""
var fullImageSelectedName = ""
var bodyParts = [BodyPart]()
required init?(map: Map) {
}
// Mappable
func mapping(map: Map) {
frontBackSide <- map["frontBackSide"]
fullImageName <- map["fullImageName"]
fullImageSelectedName <- map["fullImageSelectedName"]
bodyParts <- map["bodyParts"]
}}
이 파서는 제네릭을 사용하여 JSON을 Swift 유형으로 캐스트하여 입력해야하는 코드를 줄입니다.
https://github.com/evgenyneu/JsonSwiftson
struct Person {
let name: String?
let age: Int?
}
let mapper = JsonSwiftson(json: "{ \"name\": \"Peter\", \"age\": 41 }")
let person: Person? = Person(
name: mapper["name"].map(),
age: mapper["age"].map()
)
다음은 Swift Playground 예제입니다.
import UIKit
let jsonString = "{\"name\": \"John Doe\", \"phone\":123456}"
let data = jsonString.data(using: .utf8)
var jsonObject: Any
do {
jsonObject = try JSONSerialization.jsonObject(with: data!) as Any
if let obj = jsonObject as? NSDictionary {
print(obj["name"])
}
} catch {
print("error")
}
스위프트 4
프로젝트 생성
버튼과 UITableview로 스토리 보드 디자인하기
TableViewCell VC 생성
In Button Action 다음 코드 삽입
API에서 데이터 배열을 가져 오기 위해이 코드 기억
import UIKit
class ViewController3: UIViewController,UITableViewDelegate,UITableViewDataSource {
@IBOutlet var tableView: UITableView!
var displayDatasssss = [displyDataClass]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return displayDatasssss.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell1") as! TableViewCell1
cell.label1.text = displayDatasssss[indexPath.row].email
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func gettt(_ sender: Any) {
let url = "http://jsonplaceholder.typicode.com/users"
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "GET"
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)
let task = session.dataTask(with: request){(data, response,error)in
if (error != nil){
print("Error")
}
else{
do{
// Array of Data
let fetchData = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! NSArray
for eachData in fetchData {
let eachdataitem = eachData as! [String : Any]
let name = eachdataitem["name"]as! String
let username = eachdataitem["username"]as! String
let email = eachdataitem["email"]as! String
self.displayDatasssss.append(displyDataClass(name: name, username: username,email : email))
}
self.tableView.reloadData()
}
catch{
print("Error 2")
}
}
}
task.resume()
}
}
class displyDataClass {
var name : String
var username : String
var email : String
init(name : String,username : String,email :String) {
self.name = name
self.username = username
self.email = email
}
}
이것은 사전 데이터 가져 오기를위한 것입니다.
import UIKit
class ViewController3: UIViewController,UITableViewDelegate,UITableViewDataSource {
@IBOutlet var tableView: UITableView!
var displayDatasssss = [displyDataClass]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return displayDatasssss.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell1") as! TableViewCell1
cell.label1.text = displayDatasssss[indexPath.row].email
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func gettt(_ sender: Any) {
let url = "http://jsonplaceholder.typicode.com/users/1"
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "GET"
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)
let task = session.dataTask(with: request){(data, response,error)in
if (error != nil){
print("Error")
}
else{
do{
//Dictionary data Fetching
let fetchData = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! [String: AnyObject]
let name = fetchData["name"]as! String
let username = fetchData["username"]as! String
let email = fetchData["email"]as! String
self.displayDatasssss.append(displyDataClass(name: name, username: username,email : email))
self.tableView.reloadData()
}
catch{
print("Error 2")
}
}
}
task.resume()
}
}
class displyDataClass {
var name : String
var username : String
var email : String
init(name : String,username : String,email :String) {
self.name = name
self.username = username
self.email = email
}
}
활용 JSONDecoder().decode
Swift 4로 JSON 구문 분석 비디오보기
struct Post: Codable {
let userId: Int
let id: Int
let title: String
let body: String
}
URLSession.shared.dataTask(with: URL(string: "https://jsonplaceholder.typicode.com/posts")!) { (data, response, error) in
guard let response = response as? HTTPURLResponse else {
print("HTTPURLResponse error")
return
}
guard 200 ... 299 ~= response.statusCode else {
print("Status Code error \(response.statusCode)")
return
}
guard let data = data else {
print("No Data")
return
}
let posts = try! JSONDecoder().decode([Post].self, from: data)
print(posts)
}.resume()
Swift 2 iOS 9
let miadata = NSData(contentsOfURL: NSURL(string: "https://myWeb....php")!)
do{
let MyData = try NSJSONSerialization.JSONObjectWithData(miadata!, options: NSJSONReadingOptions.MutableContainers) as? NSArray
print(".........\(MyData)")
}
catch let error as NSError{
// error.description
print(error.description)
}