2016-11-22 3 views
0

мне нужно создать для отправки JSON с API REST:Swift Создание 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

Вы используете быстрый 3? – dirtydanee

+0

Нет, swift 2.3 @dirtydanee –

+0

Так в чем ваш вопрос? Что случилось с кодом, который вы опубликовали? (BTW, нет никакой причины, кроме тестирования для преобразования вашего вывода 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

Я понимаю ваш код, теперь я позабочусь о своем приложении, спасибо бровью, если у меня есть другие вопросы, я публикую здесь! –

Смежные вопросы