Raijen
Raijen

Reputation: 48

Creating a certain JSON data structure in Swift

For backend communication, my app requires a method to create a certainly structured JSON, and thats where i struggle. The created JSON is supposed to look like this:

{    
"data": {    
"color":"yellow",    
"size":"big"    
}    
}    

Serializing a Dictionary with the required Data does not really seem to have the option to format the content properly, my best results look like this:

Optional({    
Kategorie = Strassenschaeden;    
PLZ = 46282;    
Strasse = Erftweg;    
Unterkategorie = Schlagloch;    
})    

I didnt find any helpful weblinks for my problem, and since im new to Swift and its documentation Im kinda stuck at the moment. So my questions are: Whats the preferred data structure for my JSON data (Dictionary/Array) and how do I create a JSON that is well-formated? Thanks in advance :)

Edit: This is the interesting part of what i have used to achieve my "best result":

var data: [String: String] = ["Kategorie": "\(Kategorie)", "Unterkategorie": "\(Unterkategorie)", "Strasse": "\(Strasse)","PLZ": "\(PLZ)"]

self.post(data, url: "http://*************") { (succeeded: Bool, msg: String) -> () in
        var alert = UIAlertView(title: "Success!", message: msg, delegate: nil, cancelButtonTitle: "Okay.")

func post(params : Dictionary<String, String>, url : String, postCompleted : (succeeded: Bool, msg: String) -> ()) {
    var request = NSMutableURLRequest(URL: NSURL(string: url)!)

let JSONData:NSData = NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions.PrettyPrinted, error: &err)!
var json = NSJSONSerialization.JSONObjectWithData(JSONData, options: nil, error: &err) as? NSDictionary
println(json)

Upvotes: 1

Views: 479

Answers (2)

ramacode
ramacode

Reputation: 924

Just an itch, that no one here recommend swiftyJSON for working with JSON in Swift.

Try it, you will lose your pain of dealing with JSON. https://github.com/SwiftyJSON/SwiftyJSON

To Read JSON

let jsonData = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
let jsonObject = JSON(data: jsonData!)

To Write JSON

let jsonString = jsonObject.rawString()

Upvotes: 0

Martin R
Martin R

Reputation: 539715

Here

let JSONData:NSData = NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions.PrettyPrinted, error: &err)!
var json = NSJSONSerialization.JSONObjectWithData(JSONData, options: nil, error: &err) as? NSDictionary

you are converting the params dictionary to JSON data – and then you convert the JSON data back do a dictionary! What you probably want is to create a string from the JSON data:

let jsonData = NSJSONSerialization.dataWithJSONObject(params, options: .PrettyPrinted, error: &err)!
let json = NSString(data: jsonData, encoding: NSUTF8StringEncoding)!
println(json)

Remarks:

  • Properties and variables should have names starting with lower case letters, e.g. jsonData.
  • The explicit type annotation :NSData is not needed here, the Swift compiler can infer the type automatically.
  • The option can be given as .PrettyPrinted instead of NSJSONWritingOptions.PrettyPrinted, the compiler infers the enumeration type automatically.
  • Instead of forced unwrapping with ! you should use optional binding to check for success.

Upvotes: 2

Related Questions