Swift上的JSON:Array to String / TextField Text

时间:2016-04-28 05:54:38

标签: arrays json swift swift2

我想在文本字段上显示JSON数组的问题。 JSON取自URL。这是JSON结构:

    {
    description = „This is short decripton”;
    );
    more-description =     (
        „this is first line”,
        „this is second line”,
        „third line”,
        „etc”,
        „etc”
    );
    one-more-description =     (
        „this is first line”,
        „this is second line”,
        „third line”,
        „etc”,
        „etc”
    );

这是我的代码:

    import UIKit

    class RecipeViewController: UIViewController {
    @IBOutlet weak var descriptionTextField: UITextView!
    @IBOutlet weak var more-descriptionTextField: UITextView!
    @IBOutlet weak var one-more-descriptionTextField: UITextView!


    override func viewDidLoad() {
        super.viewDidLoad()

    let urlAsString = "http://JSON-Address.com"
    let url = NSURL(string: urlAsString)!
    let urlSession = NSURLSession.sharedSession()


    let jsonQuery = urlSession.dataTaskWithURL(url, completionHandler: { data,   response, error -> Void in
    do {
        if let jsonDate = data, let jsonResult = try      NSJSONSerialization.JSONObjectWithData(jsonDate, options: []) as? NSDictionary {
            print(jsonResult)

            let jsonDescription = jsonResult["description"] as? String
            print("result: \(jsonDescription)")

            let jsonMoreDescrp: AnyObject? = jsonResult["more-description"] as? Array<AnyObject>
            print("result: \(jsonMoreDescrp)")

            let jsonOneMoreDescrp: AnyObject? = jsonResult["one-more-description"] as? Array<AnyObject>
            print("result: \(jsonOneMoreDescrp)")

            dispatch_async(dispatch_get_main_queue(),{

              self.descriptionTextField.text = jsonDescription
               self.more-descriptionTextField.text = jsonMoreDescrp as? String
                self.one-more-descriptionTextField.text = jsonOneMoreDescrp as? String

            });


        }
    } catch let error as NSError {
        print(error)
    }


    })
    jsonQuery.resume()
    }


    override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
    }

问题在于jsonMoreDescrp&amp; jsonOneMoreDescrp。虽然我已将其更改为String,但在运行Xcode后结果为空。 jsonDescription当然有效,但这只是简单的字符串。

I know I'm doing something wrong with Array, but - can you tell me what?

4 个答案:

答案 0 :(得分:0)

jsonMoreDescrp&amp; jsonOneMoreDescrp是数组。所以,你可以像这样打电话

  self.more-descriptionTextField.text = jsonMoreDescrp[indexValue] as? String
  self.one-more-descriptionTextField.text = jsonOneMoreDescrp[indexValue] as? String

希望这会对你有所帮助。

答案 1 :(得分:0)

[已更新]由于Sudhir发现代码中也存在错误,请尝试使用以逗号分隔的字符串:

dispatch_async(dispatch_get_main_queue(),{

              self.descriptionTextField.text = jsonDescription
               self.more-descriptionTextField.text = (jsonMoreDescrp as? [String])?.joinWithSeparator(",") ?? ""
                self.one-more-descriptionTextField.text = (jsonOneMoreDescrp as? [String])?.joinWithSeparator(",") ?? ""
            });

在使用http://jsonlint.com/

之前在线验证JSON结构

有效的JSON:

{
    "description": "This is short decription",
    "more-description": [
        "this is first line",
        "this is second line",
        "third line",
        "etc",
        "etc"
    ],
    "one-more-description": [
        "this is first line",
        "this is second line",
        "third line",
        "etc",
        "etc"
    ]
}

答案 2 :(得分:0)

尝试这种方式,如果不起作用,请将您遇到的错误评论给我。

self.more-descriptionTextField.text = jsonMoreDescrp[indexValue].stringValue
self.one-more-descriptionTextField.text = jsonOneMoreDescrp[indexValue].stringValue

indexValue是您在json中想要的值的关键。

答案 3 :(得分:0)

试试这段代码,它很容易使用。 首先将地图的所有元素解析为变量,然后通过了解刚刚创建的变量的结构来执行您想要的操作。

let task = session.dataTask(with: url!) {
        (data, response, error) in
        do {
           let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject]
            if let desc = json["description"] as? String,
               let moreDesc = json["more-description"] as? [String],
               let oneMoreDesc = json["one-more-description"] as? [String] {
               dispatch_async(dispatch_get_main_queue(),{

           self.descriptionTextField.text = moreDesc
           self.more-descriptionTextField.text = moreDesc.joinWithSeparator("/n")
           self.one-more-descriptionTextField.text = oneMoreDesc.joinWithSeparator("/n")

        });

               }

        } catch let error {
            print (error)
        }
    }

    task.resume()

我没有测试过,但它应该可行。随意问。