0

I am newly to Swift programming. I have to send below JSON request to server using httpRequest in Swift3.

{
    "CompanyId": 162,
    "RollupYear": 2018,
    "UserId": 1609,
    "datarollup": [{
            "Name": "Thank You Cards",
            "RollupYear": 2018,
            "DataRollupColumnID": 210,
            "CurrentValue": 520
        },
        {
            "Name": "Prospecting Calls",
            "RollupYear": 2018,
            "DataRollupColumnID": 212,
            "CurrentValue": 1300
        }
    ],
    "Seasonalitylist": [{
            "CompanyPeriodId": 386,
            "UserId": 1609,
            "Seasonality": 25
        },
        {
            "CompanyPeriodId": 387,
            "UserId": 1609,
            "Seasonality": 25
        }
    ]
}

So, in order to send JSON in this format I have created an Entity Class with name 'RequestModel' :

import Foundation

class RequestModel {

    var CompanyId: Int? = 0
    var RollupYear: Int? = 0
    var UserId: Int? = 0

    var dataRollupArr = NSMutableArray()
    var seasonalityArr = NSMutableArray() 
}

class DataRollupModel {
    var Name: String? = ""
    var CurrentValue: Float? = 0.0
    var RollupYear: Int? = 0
    var DataRollupColumnID: Int? = 0
}

class SeasonalityModel {

    var CompanyPeriodId: Int? = 0
    var UserId: Int? = 0
    var Seasonality: Int? = 0 
}

I have all my values, Can anyone suggest me how to add my Entity values to required JSON.

Note:

Here is my code to send JSON request to server for Login :

func login(email:String, password:String, completion:@escaping (NSDictionary) -> ()) {
        if let url = NSURL(string: baseurl+"login") {
            let request = NSMutableURLRequest( url: url as URL)

            let signInDict = ["UserName":email,"Password":password]

            print(signInDict)

            let jsonData = try! JSONSerialization.data(withJSONObject: signInDict, options: JSONSerialization.WritingOptions.init(rawValue: 0))

            request.httpMethod = "POST"

            request.setValue("application/json", forHTTPHeaderField: "Content-Type")
            request.setValue("732rguiqfw9237ryu4k2141", forHTTPHeaderField: "KEY")

            request.httpBody = jsonData
            let task = URLSession.shared.dataTask(with: request as URLRequest) {
                data, response, error in
                do{
                    if let data = data,
                        let jsonString =  try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary
                        , error == nil {
                        completion(jsonString)
                    } else {
                        print("error=\(error!.localizedDescription)")
                        let errorDict = ["error_status":true,"message":error!.localizedDescription] as [String : Any]
                        completion(errorDict as NSDictionary)

                    }
                }
                catch{
                    print("error=\(error.localizedDescription)")
                    let errorDict = ["error_status":true,"message":error.localizedDescription] as [String : Any]
                    completion(errorDict as NSDictionary)

                }

            }
            task.resume()
        }
    }
user2786
  • 656
  • 4
  • 13
  • 35

2 Answers2

2

Hi first of all you don't have to create object if you already have a dictionary of the data you can directly convert it to json as shown here

I would suggest you to use object mapper as thats the easiest way if you still want to use object models

Object mapper widely used

The structs or objects that inherit the mappable class they have direct function to convert object to jsonString or the dictionary

Kunal_D
  • 29
  • 4
0

Using Swift 4 Codable, #simple like

class RequestModel: Codable {

    var CompanyId: Int? = 0
    var RollupYear: Int? = 0
    var UserId: Int? = 0

    var datarollup = [DataRollupModel]()
    var Seasonalitylist = [SeasonalityModel]()

    class DataRollupModel: Codable {
        var Name: String? = ""
        var currentValue: Float? = 0.0
        var RollupYear: Int? = 0
        var DataRollupColumnID: Int? = 0
        var CurrentValue: Int? = 0
    }

    class SeasonalityModel: Codable {

        var CompanyPeriodId: Int? = 0
        var UserId: Int? = 0
        var Seasonality: Int? = 0
    }

}

extension Encodable {
    func toJSONData() -> Data? {
        return try? JSONEncoder().encode(self)
    }
}

Use

let instance = RequestModel()
let jsonData = instance.toJSONData()
SPatel
  • 4,768
  • 4
  • 32
  • 51
  • Thank you for your time @SPatel Please see my edit, I want to know that I have values for all. Can you show me how can I pass my values to this Modal. – user2786 May 16 '18 at 13:21