swift send array to web service parameters - arrays

I want to send array object to web service, but when I try to add array to parameters it gives error. I tried many things but nothing found usefully.
I want to add ("assignees" : newList) in parameter and than send it to web service
Here is my code
var newList = [Assignee]()
var assignee = Assignee()
for u in task.NewWorkList! {
assignee = Assignee()
assignee.assignedEmail = u.Email
assignee.assignedName = u.Name
assignee.assignedSurname = u.Surname
assignee.assignedType = "PERSONEL"
assignee.assignedTo = String(u.Id!)
newList.append(assignee)
}
// in this part newList is an array of assignees.
var assigneeListString = ""
let jsonEncoder = JSONEncoder()
do {
let jsonData = try jsonEncoder.encode(newList)
assigneeListString = String(data: jsonData, encoding: .utf8)!
print("assigneeListString:",assigneeListString)
} catch {
print("error:::")
}
var parameters = [
"taskType" :
[
"code" : "OTHER"
],
"complateButtons": "COMPLATE",
"assignees" : [JSON(assigneeListString)], // does not work
// "assignees" : [JSON(newList)], // does not work
// "assignees" : JSON(newList), // does not work
// "assignees" : newList, // does not work
// "assignees" : assigneeListString, // does not work
"repeatTimeType":"NEVER"
] as [String : Any]
print("parameters:",parameters)
DAL.Service.MakeRequest(url: Constants.Service.Url.newTask,
parameters : parameters,
httpMethod : ServiceMethods.post.rawValue,
resultFunc: serviceResultFunc)
when I print parameters assignee section adds extra semi colon,
[[{"assignedTo":"63659","assignedSurname":"DAVID","assignedType":"PERSONEL","assignedName":"JOE","assignedEmail":"joe#abc.com"},{"assignedTo":"21026","assignedSurname":"GEORGE","assignedType":"PERSONEL","assignedName":"MICHAEL","assignedEmail":"michael#abc.com"}]],
when I manually add assignees to patameters , its ok.
[["assignedTo":"63659","assignedSurname":"DAVID","assignedType":"PERSONEL","assignedName":"JOE","assignedEmail":"joe#abc.com"},{"assignedTo":"21026","assignedSurname":"GEORGE","assignedType":"PERSONEL","assignedName":"MICHAEL","assignedEmail":"michael#abc.com"]],

I solved the problem with below code:
var assigneesList = [[String:Any]]()
for a in task.YeniGorevAtamaList! {
assigneesList.append(
["assignedTo":(a.Id) ?? "0",
"assignedSurname":a.Surname ?? "",
"assignedType":a.assignedType ?? "PERSONEL",
"assignedName":a.Name ?? "",
"assignedEmail":a.Email as Any
]
);
}
let parameters = [
"taskType" :
[
"code" : "DIGER"
],
"assignees" : assigneesList ,
"taskUrls" :
[
]
] as [String : Any]

Related

How to get specific element from array of type any in swift?

JSON file:
[
{
"name" : "Tom Harrys",
"email" : "tommyHarrys#abc.com",
"password" : "tomharry123"
},
{
"name" : "Sam Billing",
"email" : "samybilling#abc.com",
"password" : "sambillings789"
},
{
"name" : "Adam Gosh",
"email" : "adagoshy#abc.com",
"password" : "adamghosy989"
}
]
UTIL file:
class Utils {
static func loadData(filename : String) -> [Any] {
let filePath = Bundle(for: self).path(forResource: filename, ofType: "json") ?? "default"
let url = URL(fileURLWithPath: filePath)
do {
let data = try Data(contentsOf: url)
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
let exampleArray = json as! [Any]
if exampleArray.isEmpty {
XCTFail("Source file \(filename) is empty.")
}
return exampleArray
}
catch {
XCTFail("Error: \(error)")
XCTFail("File \(filename) not found.")
return []
}
}
}
Test file:
func loginAccount() {
let dataSource = Utils.loadData(filename: "example")
dataSource.contains(where: { ($0.name == "Sam Billing"})
}
In this code dataSource got 3 value same as Json file.
Now I want to fill the sign up form with specific value
( "name" : "Sam Billing",
"email" : "samybilling#abc.com",
"password" : "sambillings789"
)
from the array.
You should not be using JSONSerializer in Swift. A better option is a JSONDecoder. JSONDecoder will allow you to establish and preserve the type information for the data you've decoded. Here is an Playground example of how you would use JSONDecoder to handle this data set, then one technique extract Sam's record from the array of users.
import UIKit
import Foundation
let JSONContent = """
[
{
"name" : "Tom Harrys",
"email" : "tommyHarrys#abc.com",
"password" : "tomharry123"
},
{
"name" : "Sam Billing",
"email" : "samybilling#abc.com",
"password" : "sambillings789"
},
{
"name" : "Adam Gosh",
"email" : "adagoshy#abc.com",
"password" : "adamghosy989"
}
]
""".data(using: .utf8)!
struct UserRecord : Decodable {
let name : String
let email: String
let password: String // Don't pass passwords in plain text around in JSON
}
class Utils {
static func loadData() -> [UserRecord] {
do {
let decoder = JSONDecoder()
let data = JSONContent
let json = try decoder.decode([UserRecord].self, from: data)
return json
}
catch let error {
print("The json could not be decoded \(error)")
return []
}
}
}
let users = Utils.loadData()
if let sam = users.first(where: { user in user.email.caseInsensitiveCompare("samybilling#abc.com") == .orderedSame }) {
debugPrint(sam)
} else {
print("Sam was missing")
}

How to convert model with array to JSON array Swift 3

i have some question and solution, i have class model and it has array inside, my model like this
class WillModel{
var name: String = ""
var documents:[WillItems] = []
var isLFStatus : Bool = false
var isLFShared : Bool = false
}
class WillItems{
var documentPath: String = ""
var documentRemark: String = ""
}
i want to convert the result to JSON Array like
{
"name" : "value",
"documents" : [
{
"documentPath" : "value"
"documentRemark" : "value"
},
{
"documentPath" : "value2"
"documentRemark" : "value2"
}
],
"isLFStatus" : true,
"isLFShared" : true
}
i'm using Swift 3, thanks for your solutions
You can write a simple method to manually encode your model to json as below,
func encodeWillModel(_ model: WillModel) -> [String: Any] {
var params: [String: Any] = [:]
params["name"] = model.name
params["documents"] = model.documents.map({["documentPath": $0.documentPath,
"documentRemark": $0.documentRemark]})
params["isLFStatus"] = model.isLFStatus
params["isLFShared"] = model.isLFShared
return params
}
and you can pass any model to get the json something like,
let willModelJSON = encodeWillModel(yourModel)
But a better approach would be to use any json parsing library(SwiftyJSON, ObjectMapper) that supports Swift 3 or upgrade to Swift 4 and use Encodable/Decodable

Getting specific value from Swift array

So, I'm download data from an API using SwiftyJSON. I'm converting it, and looping through to get all of the results. I'm trying to get a specific part of each result to print out, but I can't seem to get it working.
The code I'm using below takes the json, and loops through it and prints out what is also below. From what is printed, I just want to get the "subject".
do {
let jsonObj = try JSONSerialization.jsonObject(with: data, options: []) as! [String: AnyObject]
let json = JSON(jsonObj)
let pms: NSArray = json["result"]["pms"].arrayValue as NSArray
let arrayLength = pms.count
for var i in (0..<arrayLength) {
let pm = pms[i]
i+=1
}
} catch let error as NSError {
print(error)
}
Which then gives values like:
{
"subject" : "Example",
"status" : 1,
"recipient" : 012345,
"recipientusername" : "Example",
"dateline" : "2018-01-01",
"sender" : 012345,
"pmid" : 012345,
"senderusername" : "DoctorSheep"
}
{
"subject" : "Example 2",
"status" : 1,
"recipient" : 678910,
"recipientusername" : "Example 2",
"dateline" : "2018-01-01",
"sender" : 678910,
"pmid" : 678910,
"senderusername" : "Example 2"
}
If I try something like
let subject = pm["subject"]
I get an error that "Type 'Any' has no subscript members".
let pms = json["result"]["pms"].arrayValue as Array
let arrayLength = pms.count
for var i in (0..<arrayLength) {
let pm = pms[i]
let subject = pm["subject"]
print(subject)
i+=1
}

SwiftyJSON Append new data to existing JSON array

I am working on a way to add new JSON data to my existing JSON array:
var resources: JSON = [
"resources": []
]
override func viewDidLoad() {
super.viewDidLoad()
getApiResourceA() { responseObject, error in
var resourceA: JSON = [
"resourceA": []
]
let resourceAResponseObject = JSON(responseObject!)
resourceA["resourceA"] = resourceAResponseObject
self.resources["resources"] = resourceA
}
getApiResourceB() { responseObject, error in
var resourceB: JSON = [
"resourceB": []
]
let resourceBResponseObject = JSON(responseObject!)
resourceB["resourceB"] = resourceBResponseObject
self.resources["resources"] = resourceB
}
}
The structure I am trying to get is:
{
"resources": {
"resourceA": {
"id": 1
"name": "Name1"
}
"resourceB": {
"id": 2
"name": "Name2"
}
}
}
But in my code there are two different "resources"-array created...
Anyone know how to deal with this?
First it is important to understand that JSON is Struct means it is duplicated every time you pass it or use it.
Another issue, you declared resources as Array and not as Dictionary means you can use resource as key.
Declare extensions:
extension JSON{
mutating func appendIfArray(json:JSON){
if var arr = self.array{
arr.append(json)
self = JSON(arr);
}
}
mutating func appendIfDictionary(key:String,json:JSON){
if var dict = self.dictionary{
dict[key] = json;
self = JSON(dict);
}
}
}
use:
//notice the change [String:AnyObject]
var resources: JSON = [
"resources": [String:AnyObject](),
]
resources["resources"].appendIfDictionary("resourceA", json: JSON(["key1":"value1"]))
resources["resources"].appendIfDictionary("resourceB", json: JSON(["key2":"value2"]))
result:
{
"resources" : {
"resourceB" : {
"key2" : "value2"
},
"resourceA" : {
"key1" : "value1"
}
}
}
#daniel-krom has right, but is a little confusing implement the extension, so, we need only add at the end of the Swift controller (or class) that code that adds the "append" methods, nothing else.
Using the appendIfArray method, I could pass from this
[
{
"id_usuario" : 2
}
]
...to this
[
{
"id_usuario" : 2
},
{
"id_usuario" : 111
},
{
"id_usuario" : 112
},
{
"id_usuario" : 113
}
]
The complete code is below:
do{
try json2!["usuarios"][indice]["fotos"][0]["me_gusta"].appendIfArray(json: JSON( ["id_usuario": 111] ))
try json2!["usuarios"][indice]["fotos"][0]["me_gusta"].appendIfArray(json: JSON( ["id_usuario": 112] ))
try json2!["usuarios"][indice]["fotos"][0]["me_gusta"].appendIfArray(json: JSON( ["id_usuario": 113] ))
}catch {
print("Error")
}
The complete JSON structure can find in
http://jsoneditoronline.org/?id=56988c404dcd3c8b3065a583f9a41bba
I hope this can be useful

why the error: fatal error: Array index out of range? [swift]

Please find error location in the below image :
The number of values in tripOption will change in each request.
There a logic problem in the code where the tripOption for example outputs just 2 values.. but the loop keeps going and says array out of index.. i have no idea how to fix this issue.
var arrayOfFlights : [FlightDataModel] = [FlightDataModel]()
if json != nil {
//insert airline data into arrayOfFlights
if let myJSON = json as? [String:AnyObject] {
if let trips = myJSON["trips"] as? [String:AnyObject] {
if let data = trips["data"] as? [String:AnyObject] {
if let carriers = data["carrier"] as? [[String:String]] {
for (index, carrierName) in enumerate(carriers) {
var myFlight = FlightDataModel(airline: carrierName["name"] as String!, price:nil)
self.arrayOfFlights.append(myFlight)
println("\(self.arrayOfFlights[index].airline!)")
}
}
}
if var tripOptions = trips["tripOption"] as? [[String:String]] {
for (index, tripOption) in enumerate(tripOptions) {
self.arrayOfFlights[index].price = tripOption["saleTotal"] as String!
println("price \(self.arrayOfFlights[index].price!)")
}
}
}
}
parameteers in url jsjon request:
var parameters = [
"request": [
"slice": [
[
"origin": from,
"destination": to,
"date": when
]
],
"passengers": [
"adultCount": 1,
"infantInLapCount": 0,
"infantInSeatCount": 0,
"childCount": 0,
"seniorCount": 0
],
"solutions": 5,
"refundable": false
]
]
The error is because you are trying to access an element in arrayOfFlights with an index greater than its size - 1.
// index > no of existing elements in the array
self.arrayOfFlights[index].price = tripOption["saleTotal"] as String!
Maybe you are trying to push new elements into an empty array?
self.arrayOfFlightPrices.append(tripOption["saleTotal"] as String!)
You should simplify your code and perhaps use the first iteration of the results to ensure you don't go out of bounds. Something LIKE this:
var arrayOfFlights : [FlightDataModel] = [FlightDataModel]()
if let data = json as? NSDictionary {
if let carriers = data.valueForKeyPath("trips.data.carrier") as? NSArray {
for (index, carrier) in enumerate(carriers) {
var myFlight = FlightDataModel(airline: carrier["name"] as String!, price:nil)
arrayOfFlights.append(myFlight)
}
}
if let trips = data.valueForKey("trips") as? NSArray where arrayOfFlights.count > 0 {
for (index, carrier) in enumerate(arrayOfFlights) {
carrier.price = trips.objectAtIndex(index)["saleTotal"] as String!
}
}
}

Resources