简体   繁体   中英

parse string and send as Json in swift

I have real big problem finding the right code which helps me to parse String to JSON and then send to external server. I'm using xCode 6.1, so some ways of parsing won't work for me, like SwiftyJSON.

On internet i only can find the way to send String , but not JSON, or if i found something it won't work.

I'm beginner in iOS and it would really help me if someone can explain me how to do it.

Thank you a lot.

If you have JSON String convert to NSData object.Check the data object before sending to an external server if data is valid JSON format or not by using NSJSONSerialization.I am giving sample code to how can check JSON Data valid or not.

suppose you String is like this,

let jsonString = "{\"device\":\"iPhone 6\",\"OS\":\"iOS 9\",\"name\":\"Apple\"}"
        let data = jsonString.dataUsingEncoding(NSUTF8StringEncoding)
        do {
            let responseData = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)
            if responseData != nil { // valid JSON
                //Now pass data object to server
            }

        } catch {
            NSLog("ERROR when parse JSON")
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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