2

I got an array of object like this

    var AuditActivityDayListJson =  Array<AuditActivityDayModel>()


    class AuditActivityDayModel : Serializable {
    var DayNumber : Int
    var DayType : Int
    var DayDateDisplay : String
    var DayDate : String

    override init() {
        DayNumber = 0
        DayType = 0
        DayDateDisplay = ""
        DayDate = ""
    }
}

How can i convert it into json string like this

[{"DayType":1,"DayNumber":1,"DayDate":"2015-06-30", "DayDateDisplay":""},{"DayType":1,"DayNumber":2,"DayDate":"2015-07-01","DayDateDisplay":""}]

Thanks all for your answer . Please help.

1

1 Answer 1

5

If you want to use builtin functions like NSJSONSerialization ( https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSJSONSerialization_Class/ ) you basically need to convert all your objects to arrays, dictionaries, strings and numbers

In your case this should work, converting your objects to dictionaries before converting to a JSON string:

    let jsonCompatibleArray = AuditActivityDayListJson.map { model in
        return [
            "DayNumber":model.DayNumber,
            "DayType":model.DayType,
            "DayDateDisplay":model.DayDateDisplay,
            "DayDate":model.DayDate
        ]
    }
    let data = NSJSONSerialization.dataWithJSONObject(jsonCompatibleArray, options: nil, error: nil)
    let jsonString = NSString(data: data!, encoding: NSUTF8StringEncoding)

For more complex scenarios I recommend SwiftyJSON ( https://github.com/SwiftyJSON/SwiftyJSON ) which makes error handling and more much easier.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.