简体   繁体   English

如何快速从带有 json 的 URL 获取 JSON 响应

[英]How to get JSON response from URL with json inside in swift

Hi my url of request is:嗨,我的请求网址是:

http://MYDOMAIN/jsonrpc?request=
{"jsonrpc": "2.0", "method": "VideoLibrary.GetMovies", "params": { "filter": {"field": "playcount", "operator": "is", "value": "0"}, "limits": { "start" : 0, "end": 75 }, "properties" : ["art", "rating", "thumbnail", "playcount", "file"], "sort": { "order": "ascending", "method": "label", "ignorearticle": true } }, "id": "libMovies"}

How can I parse result in swift?如何快速解析结果?

Use Codable to parse JSON.使用 Codable 解析 JSON。 Try with your demo input.尝试使用您的演示输入。

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var myView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let someString = """
        {"jsonrpc": "2.0", "method": "VideoLibrary.GetMovies", "params": { "filter": {"field": "playcount", "operator": "is", "value": "0"}, "limits": { "start" : 0, "end": 75 }, "properties" : ["art", "rating", "thumbnail", "playcount", "file"], "sort": { "order": "ascending", "method": "label", "ignorearticle": true } }, "id": "libMovies"}
"""

        let data = someString.data(using: .utf8)!
            do{
                let jsonDataModels = try JSONDecoder().decode(JSONDataModel.self, from: data)
                print(String(data: data, encoding: .utf8)!)
                print("jsonDataModels: \(jsonDataModels)")
            }catch {
                print(error)
        }

    }
}

// This file was generated from JSON Schema using quicktype, do not modify it directly.
// To parse the JSON, add this file to your project and do:
//
//   let jSONDataModel = try? newJSONDecoder().decode(JSONDataModel.self, from: jsonData)

import Foundation

// MARK: - JSONDataModel
struct JSONDataModel: Codable {
    let jsonrpc, method: String
    let params: Params
    let id: String
}

// MARK: - Params
struct Params: Codable {
    let filter: Filter
    let limits: Limits
    let properties: [String]
    let sort: Sort
}

// MARK: - Filter
struct Filter: Codable {
    let field, filterOperator, value: String

    enum CodingKeys: String, CodingKey {
        case field
        case filterOperator = "operator"
        case value
    }
}

// MARK: - Limits
struct Limits: Codable {
    let start, end: Int
}

// MARK: - Sort
struct Sort: Codable {
    let order, method: String
    let ignorearticle: Bool
}

Another example tries with API call.另一个示例尝试使用 API 调用。

import UIKit
import Foundation

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let url = URL(string: "https://jsonplaceholder.typicode.com/users")!
        let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
            guard let data = data else { return }
            do{
                let jsonDataModels = try JSONDecoder().decode([JSONDataModel].self, from: data)
                print(String(data: data, encoding: .utf8)!)
                print("jsonDataModels: \(jsonDataModels)")
            }catch{}
        }
        task.resume()

    }
}


struct JSONDataModel: Codable {
    let id: Int
    let name, username, email: String
    let address: Address
    let phone, website: String
    let company: Company
}


struct Address: Codable {
    let street, suite, city, zipcode: String
    let geo: Geo
}


struct Geo: Codable {
    let lat, lng: String
}


struct Company: Codable {
    let name, catchPhrase, bs: String
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM