swift create json and parse

iOS 2015. 7. 21. 19:12
반응형

https://medium.com/swift-programming/4-json-in-swift-144bf5f88ce4


import Foundation


print("Hello, World!")


let jsonObject: [AnyObject] = [

    ["name": "John", "age": 21],

    ["name": "Bob", "age": 35],

]


print( jsonObject )


func JSONStringify( value: AnyObject, prettyPrinted:Bool = false) -> String{

    

    let options = prettyPrinted ? NSJSONWritingOptions.PrettyPrinted : NSJSONWritingOptions(rawValue: 0)

    

    if NSJSONSerialization.isValidJSONObject(value){

        

        do{

            let data = try NSJSONSerialization.dataWithJSONObject(value, options: options)

            if let string = NSString(data: data, encoding: NSUTF8StringEncoding){

                return string as String

            }

            

        }catch{

            print("error")

        }

        

    }

    return ""

}


print(JSONStringify(jsonObject, prettyPrinted: true));


-output-


Hello, World!

[{

    age = 21;

    name = John;

}, {

    age = 35;

    name = Bob;

}]

[

  {

    "age" : 21,

    "name" : "John"

  },

  {

    "age" : 35,

    "name" : "Bob"

  }

]

Program ended with exit code: 0

반응형
: