Alamofire如何在Swift中解析JSON?

huangapple go评论68阅读模式
英文:

Alamofire how to parse JSON in Swift?

问题

我使用Alamofire的GET函数从API返回这个JSON数据。
以下是我如何使用Alamofire的方法:

struct Params: Encodable {
    let code: String
    let codeType: String
}

let params = Params(code: "709532929804933", codeType: "IDENTCODE")
let headers: HTTPHeaders = [
    "Authorization": "Basic xxxHIDExxx",
    "Accept": "application/json"
]

AF.request("https://xxx.xx/cloudcrm/customer",
           method: .get,
           parameters: params,
           headers: headers).validate(statusCode: 200..<300).responseJSON { response in
            switch response.result {
                case .success:
                    debugPrint(response.value as Any)
             
                case let .failure(error):
                    print(error)
            }
       }

打印JSON数据:

{
    customerData = "<zakaznik><zkznid>475301</zkznid><titul></titul><jmeno>757B746D</jmeno><prijmeni>DÁRKOVÁ KARTA</prijmeni><rozliseni></rozliseni><osloveniok>false</osloveniok><kontos></kontos><skupzak1_klic>DK</skupzak1_klic><skupzak2_klic>default</skupzak2_klic><cenkat_klic>1</cenkat_klic><platido>2118-07-31</platido><valid>true</valid></zakaznik>";
    message = "Informace o zákazníkovi \"DÁRKOVÁ KARTA 757B746D\" načteny.";
}

我尝试查看JSON是否有效(https://jsonlint.com/),但它不是有效的JSON。在Swift中是否有解析此字符串的方法?

英文:

I used Alamofire's GET function to return this JSON from API.
Here's how I used Alamofire:

struct Params: Encodable {
            let code: String
            let codeType: String
        }

        let params = Params(code: &quot;709532929804933&quot;, codeType: &quot;IDENTCODE&quot;)
        let headers: HTTPHeaders = [
            &quot;Authorization&quot;: &quot;Basic xxxHIDExxx&quot;,
            &quot;Accept&quot;: &quot;application/json&quot;
        ]
        
        AF.request(&quot;https://xxx.xx/cloudcrm/customer&quot;,
                   method: .get,
                   parameters: params,
                   headers: headers).validate(statusCode: 200..&lt;300).responseJSON { response in
                    switch response.result {
                            case .success:
                                debugPrint(response.value as Any)
                         
                    case let .failure(error): 
                                print(error)
                            }
                   }

        
Print json:
{
    customerData = &quot;&lt;zakaznik&gt;&lt;zkznid&gt;475301&lt;/zkznid&gt;&lt;titul&gt;&lt;/titul&gt;&lt;jmeno&gt;757B746D&lt;/jmeno&gt;&lt;prijmeni&gt;D\U00c1RKOV\U00c1 KARTA&lt;/prijmeni&gt;&lt;rozliseni&gt;&lt;/rozliseni&gt;&lt;osloveniok&gt;false&lt;/osloveniok&gt;&lt;kontos&gt;&lt;/kontos&gt;&lt;skupzak1_klic&gt;DK&lt;/skupzak1_klic&gt;&lt;skupzak2_klic&gt;default&lt;/skupzak2_klic&gt;&lt;cenkat_klic&gt;1&lt;/cenkat_klic&gt;&lt;platido&gt;2118-07-31&lt;/platido&gt;&lt;valid&gt;true&lt;/valid&gt;&lt;/zakaznik&gt;&quot;;
    message = &quot;Informace o z\U00e1kazn\U00edkovi \&quot;D\U00c1RKOV\U00c1 KARTA 757B746D\&quot; na\U010dteny.&quot;;
}

I tried to see if the JSON is valid (https://jsonlint.com/), but it's not.
Is there any way to parse this string in Swift?

答案1

得分: 0

这是JSON。
它已经被解析,response.value是一个Dictionary,一个[String: Any],在您的示例中,甚至是一个[String: String]
您打印的是NSDictionary(几乎相当于Swift的Dictionary)的description,输出采用OpenStep格式。
请注意键和值之间的"=",以及行尾的";"
什么告诉我这也是JSON?您在success情况下打印它,所以它成功将数据解析为"JSON"对象。

如果您想要查看实际接收到的"JSON"数据:

let responseStr = String(data: response.data!, encoding: .utf8)
print("Received: \(responseStr)")

现在,responseJSON已被弃用,请使用CodableresponseDecodable(of:)

如果您仍不想使用Codable

if let dict = response.value as? [String: Any] {
    if let customerData = dict["customerData"] as? String {
        print("customerData: \(customerData)")
        // 解析XML
    }
    if let message = dict["message"] as? String {
        print("message: \(message)")
    }
}
英文:

It's JSON.<br>
It has already been parsed and response.value is a Dictionary, a [String: Any], and in your sample case, even a [String: String].<br>
What you printed is the description of a NSDictionary (more or less a Swift Dictionary), and the output is in OpenStep Format.
Notice the: &quot;=&quot; between key & value, and the ";" at the end of the line.
What tells me that's also JSON? You printed it in the success case, so it succeed parsing the Data into "JSON" object.

If you want to see the actual "JSON" data you received:

let responseStr = String(data: response.data!, encoding: .utf8)
print(&quot;Received: \(responseStr)&quot;)

You should see it's valid JSON.

Now, responseJSON is deprecated, please use Codable and responseDecodable(of:).

If you still don't want to use Codable:

if let dict = response.value as? [String: Any] {
    if let customerData = dict[&quot;customerData&quot;] as? String {
        print(&quot;customerData: \(customerData)&quot;)
        //Parse the XML
    }
    if let message = dict[&quot;message&quot;] as? String {
        print(&quot;message: \(message)&quot;)
    }
}

huangapple
  • 本文由 发表于 2023年6月8日 07:09:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76427623.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定