分类 json 下的文章

swift直接传输json字串

客户端

//
//  ViewController.swift
//  http请求
//
//  Created by admin on 16/2/26.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.sendJSON()
    }
    func sendJSON()
    {
        let urlStr = "http://test.com/postjson.php"
        let url = NSURL(string: urlStr.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)
        let request = NSMutableURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringCacheData, timeoutInterval: 10)
        let jsonData = ["name":"jin","age":18]
        // 检查数据类型是否能转换成json
        if NSJSONSerialization.isValidJSONObject(jsonData) == false
        {
            print("格式错误")
            exit(1)
        }
        let sendData = try? NSJSONSerialization.dataWithJSONObject(jsonData, options: NSJSONWritingOptions.PrettyPrinted)
        // 设置类型以及数据
        request.HTTPMethod = "post"
        request.HTTPBody = sendData
        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue()) { (response:NSURLResponse?, data:NSData?, error:NSError?) -> Void in
            let jsonData:AnyObject? = try? NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
            print(jsonData)
        }
    }
}

服务器

header('Content-Type:text/plain;charset=utf-8');

$json = file_get_contents('php://input');
// 反序列化JSON
$obj = json_decode($json, TRUE ); 

// 打印对象明细信息
echo json_encode($obj);

服务器返回数据解析(json,plist)

//
//  ViewController.swift
//  数据解析-json
//
//  Created by admin on 16/2/25.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.plistDecodeC()
        // Do any additional setup after loading the view, typically from a nib.
    }
    func plistDecodeC()
    {
        // url
        let url = NSURL(string: "http://test.com/plist")
        // 请求
        let request = NSURLRequest(URL: url!)
        // 发送请求
        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue()) { (responce:NSURLResponse?, data:NSData?, error:NSError?) -> Void in
            // 转换后使用
            let plist:AnyObject? = NSPropertyListSerialization.propertyListFromData(data!, mutabilityOption: NSPropertyListMutabilityOptions.MutableContainers, format: nil, errorDescription: nil)
            // 使用
            print(plist)
            print(plist?.valueForKey("CFBundleDevelopmentRegion"))
            print(plist?.valueForKey("NSAppTransportSecurity"))
        }
    }
    /**
     {
     "statuses": [
     "3382905382185354",
     "3382905252160340",
     "3382905235630562",
     ],
     "previous_cursor": 0,
     "next_cursor": 0,
     "total_number": 16
     }
     */
    func jsonDecodeB()
    {
        // url
        let url = NSURL(string: "http://test.com/jsonA")
        // 请求
        let request = NSURLRequest(URL: url!)
        // 发送请求
        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue()) { (responce:NSURLResponse?, data:NSData?, error:NSError?) -> Void in
            // 转换后使用
            let json:AnyObject? = JSONDecoder().objectWithData(data!)
            // 全部都是nil。。。。
            print(json)
            print(json?.valueForKey("statuses"))
            print(json?.valueForKey("next_cursor"))
        }
    }
    func jsonDecodeA()
    {
        // url
        let url = NSURL(string: "http://test.com/jsonA")
        // 请求
        let request = NSURLRequest(URL: url!)
        // 发送请求
        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue()) { (responce:NSURLResponse?, data:NSData?, error:NSError?) -> Void in
            // 转换后使用
            let json:AnyObject? = try? NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
            // 取出使用,都是可选类型,有点蛋疼啊
            print(json?.valueForKey("statuses"))
            print(json?.valueForKey("next_cursor"))
        }
    }
}