简体   繁体   English

Swift 2 Json解析数组并获得“ nil”

[英]Swift 2 Json Parsing Array and Get Just “nil”

I am trying to code a simple clipboard translator of myself. 我正在尝试为自己编写一个简单的剪贴板翻译器。 So I use an API but I can't get the real data in JSON. 因此,我使用API​​,但无法获取JSON中的真实数据。

Here is my Code 这是我的代码

import Cocoa

var url = NSURL(string: "http://api.fanyi.baidu.com/api/trans/vip/translate?q=%E6%B8%AC%E8%A9%A6%E7%94%A8%E6%96%87%E5%AD%97&from=cht&to=zh&appid=20160223000013220&salt=1435660288&sign=0a697bbcbd4686b168cb3255ffea1427")

var data: NSData
var json: AnyObject!


do{
    data = try NSData(contentsOfURL: url!, options: NSDataReadingOptions.DataReadingUncached)
    json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments)
}

var transInfo: AnyObject! = json.objectForKey("trans_result['dst']")

In the URL, data of trans_result["dst"] is the answer i want. 在URL中, trans_result [“ dst”]的数据是我想要的答案。 But from the code below i could only get a "nil" instead of "\测\试\用\文\字" 但是从下面的代码中,我只能得到一个“ nil”,而不是“ \\ u6d4b \\ u8bd5 \\ u7528 \\ u6587 \\ u5b57”

How can I solve this problem? 我怎么解决这个问题? Was I missing something? 我错过了什么吗?

Try this index 试试这个指数

trans_result[0].dst

Visualize the json data with codebeautify 使用codebeautify可视化json数据

You can try this 你可以试试这个

do{
    data = try NSData(contentsOfURL: url!, options: NSDataReadingOptions.DataReadingUncached)
   let json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments)

    let arrResult = json["trans_result"]
    print("Result \(arrResult!![0]["src"])")
}catch {
    print("Error in json parsing")
}

You made two mistakes here 你在这里犯了两个错误

1) You can't access the value of dst by doing objectForKey("trans_result['dst']") 1)您无法通过执行objectForKey("trans_result['dst']")访问dst的值

2) There is one more layer between trans_result and dst , that means json["trans_result"] is not Dictionary but a Array 2) trans_resultdst之间还有一层,这意味着json["trans_result"]不是Dictionary而是一个Array

In order to get the value you need and make the code safe when unwrapping Optional : 为了获得所需的值,并在展开包装时使代码安全Optional

if let array = json.objectForKey("trans_result") as? NSArray where array.count > 0{
    if let dst = array[0].objectForKey("dst") {
        print(dst)
    }
}

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

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