简体   繁体   English

在Swift中解析JSON并访问值?

[英]Parsing JSON in Swift and accessing values?

I have successfully parsed JSON for: 我已成功解析JSON:

birthday = "04/10/1986";
    id = 202038339983;
    location =     {
        city = Jupiter;
        country = "United States";
        state = FL;
    };

My question is when part of the JSON is: 我的问题是当JSON的一部分是:

    submissions =     {
     data =         (
                        {
                "created_time" = "2018-02-16T05:11:56+0000";
                id = "131448394823824_167398094382256";
                viewer = "Any random string and/or emojis";
            },

                    {
            "created_time" = "2018-02-14T23:36:41+0000";
            id = "809809871824_8908987486899";
            message = "vday \Ud83d\Udda4\U2665\Ufe0f";
        });}

How am I supposed to access created_time, id, viewer, and message? 我应该如何访问created_time,id,查看器和消息?

I have been able to print the whole submissions JSON response to the console with this code : 我已经可以使用以下代码将整个提交的JSON响应打印到控制台:

           guard let jsonD = responseFromServer as? [String : Any] else {return}
            let subs1 = (jsonD["submissions"] as? [String : Any])
            let accessSubs1 = theSubs1
            guard let parsedPost = theSubs1  else {
                return
            }

My console will display: 我的控制台将显示:

    ["data": <__NSArrayI 0x6040001a86c0>(
{
                   "created_time" = "2018-02-16T05:11:56+0000";
                    id = "131448394823824_167398094382256";
                    viewer = "Any random string and/or emojis";
                },

                        {
                "created_time" = "2018-02-14T23:36:41+0000";
                id = "809809871824_8908987486899";
                message = "vday \Ud83d\Udda4\U2665\Ufe0f";
            })]

My question is how should I parse the JSON so I can access the created_time inside submissions? 我的问题是我应该如何解析JSON,以便可以在提交中访问created_time?

Here is the HTTP Request: 这是HTTP请求:

    struct XClass: RequestProtocol {

    var Path = "/User"
    var parameters: [String : Any]? = ["stuff": "id, birthday, location, submissions"]
    var aToken = aToken.current
    var httpMethod: RequestHTTPMethod = .GET
    var apiVersion: APIVersion = .defaultVersion

    struct Response: ResponseProtocol {

        var id = String()
        var birthday = String()
        var city = String()
        var state = String()
        var country = String()
        var viewSubs = [String : Any]()



        init(XResponse: Any?) {


            guard let jsonD = XResponse as? [String : Any] else {return}
            id = (jsonD["id"] as? String)!
            birthday = (jsonD["birthday"] as? String)!
            let XArr = (jsonD["location"] as? [String : String])
            city = XArr!["city"]!
            country = XArr!["country"]!
            state = XArr!["state"]!
            let subs1 = (jsonD["submissions"] as? [String : Any])
            let accessSubs1 = theSubs1
            guard let parsedPost = theSubs1  else {
                return
            }
            viewSubs = theSubs1
            }}}

                func getXData(){
           let connection = RequestConnection()
           connection.add(XClass()) { response, result in
           switch result {
               case .success(let response):
                  print("Request Succeeded: \(response)\n\n\n")
               case .failed(let error):
                  print("Request Failed: \(error)")
          }}
              connection.start()
           }

Create a struct 创建一个结构

struct Data: Decodable {
    var created_time : String
    var id : String
    var viewer : String
}

call to the api url from URLSession 从URLSession调用api url

guard let url = URL(string: "your api url")
URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
   print(error.localizedDescription)
} else {
   guard let data = data else {return}
   var data: [Data]() = JSONDecoder().decode(Data.self, data)
   for dat in data{
       print(dat.created_time)
       print(dat.id)
       print(dat.viewer)
   }
}

If you are not using Decodable from Swift 4, or still in Swift 3, then you can specify that the data in "submissions" is an array of dictionaries (double brackets) then you can iterate that. 如果您不是在Swift 4中使用Decodable ,还是在Swift 3中仍未使用,则可以指定“提交”中的数据为字典数组 (双括号),然后可以对其进行迭代。

Change 更改

        let subs1 = (jsonD["submissions"] as? [String : Any])

To

        let subs1 = (jsonD["submissions"] as? [[String : Any]])

        for sub in subs1 {
            let time = sub["created_time "] as? [String : Any]
            ...
        }

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

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