2016-11-22 57 views
0

我需要從REST API創建發送一個JSON創建JSON:斯威夫特API REST

{ 
    "ownId": "seu_identificador_proprio", 
    "amount": { 
    "currency": "BRL", 
    "subtotals": { 
     "shipping": 1000 
    } 
    }, 
    "items": [ 
    { 
     "product": "Descrição do pedido", 
     "quantity": 1, 
     "detail": "Mais info...", 
     "price": 1000 
    } 
    ], 
    "customer": { 
    "ownId": "seu_identificador_proprio_de_cliente", 
    "fullname": "Jose Silva", 
    "email": "[email protected]", 
    "birthDate": "1988-12-30", 
    "taxDocument": { 
     "type": "CPF", 
     "number": "22222222222" 
    }, 
    "phone": { 
     "countryCode": "55", 
     "areaCode": "11", 
     "number": "66778899" 
    }, 
    "shippingAddress": { 
     "street": "Avenida Faria Lima", 
     "streetNumber": 2927, 
     "complement": 8, 
     "district": "Itaim", 
     "city": "Sao Paulo", 
     "state": "SP", 
     "country": "BRA", 
     "zipCode": "" 
    } 
    } 
} 

我感到困惑與創建..

我試着開始[NSObject:AnyObject]

var d1 : [NSObject:AnyObject] = ["ownId":"seu_identificador_proprio", "customer":""] 
    let dd1 = ["currency":"BRL"] 
    let dd2 = ["shipping":"1000"] 
    let arr = [d1] 
    let d = try! NSJSONSerialization.dataWithJSONObject(arr, options: NSJSONWritingOptions.PrettyPrinted) 
    let s = NSString(data: d, encoding: NSUTF8StringEncoding)! as String 
    print(s) 

但我需要幫助!

+0

您使用SWIFT 3? – dirtydanee

+0

沒有,SWIFT 2.3 @dirtydanee –

+0

那麼什麼是你的問題?你發佈的代碼有什麼問題? (順便說一句,沒有理由不是測試你的JSON輸出轉換從NSData的一個字符串等,也沒有理由使用漂亮的打印格式。爲了發送到一個RESTful的服務器,你不應該用漂亮的格式。) –

回答

1

我已經更新了你的代碼,增加了一些提示,你怎麼能建立上面列出的結構。快樂的編碼!

// Do not use NSObject as key's type 
// Keys in a dictionary are usually Strig in every language 
var d1: [String: AnyObject] = ["ownId":"seu_identificador_proprio", "customer":""] 

// Define the type of your dictionaries, if you dont, in this case it will create a [String:String] dictionary, but you need to insert an array into it 
// Make it a var, so you can mutate the container 
var dd1: [String: AnyObject] = ["currency":"BRL"] 
// Here the type is undefined. Try inserting anything else than String, and see the results 
let dd2 = ["shipping":"1000"] 
dd1["subtotals"] = dd2 
d1["amount"] = dd1 
// Build all your dictionaries like i did above, and at the end add all of them into arr 
let arr = [d1] 
// Do not force try any throwing function in swift - if there is an error, your application will crash 
// Use proper error handling - https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html 

do { 
let d = try NSJSONSerialization.dataWithJSONObject(arr, options: NSJSONWritingOptions.PrettyPrinted) 
let s = NSString(data: d, encoding: NSUTF8StringEncoding)! as String 
print(s) 
} catch { 
// Do your error handling here 
} 
+0

很不錯!謝謝你; D –

+0

將它標記爲已接受的答案,或者至少比可能的更快? – dirtydanee

+0

我明白你的代碼,現在我將定製我的應用程序,謝謝額頭,如果我有其他問,我張貼在這裏! –