1

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)
5
  • Did you have a look at NSJSONSerialization? There are already plenty of Q&A about the usage of that class in Swift. Commented Dec 6, 2014 at 17:18
  • Yes i did, every option of NSJSONWritingOptions does not fit to my problem, PrettyPrinted for example. Commented Dec 6, 2014 at 17:26
  • What have your tried? Commented Dec 6, 2014 at 17:35
  • Well, from your question it is not clear what you tried and how you got the "best result" (which is no JSON at all). Commented Dec 6, 2014 at 17:35
  • @Martin R NSJSONSerialization does not seem to have the options to format a JSON in the way i need it, especially concerning the semicolons and equal signs. Im aware of the fact that its not a valid JSON, even though I achieved it by using NSJSONSerialization. Any tips on options I may have interpreted wrong? Commented Dec 6, 2014 at 17:55

2 Answers 2

2

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.
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you, that's very helpful :) So my data is already in a good format, what i was concerned about was just the println of a Dictionary, right? And any idea how i can exchange the optional() to "data" { ?
@Raijen: If you look at the definition of JSONObjectWithData() then you'll see that it returns AnyObject?. The question marks indicates an optional which can be nil (for "no value") if the function "failed". Unwrapping is one way to "remove the optional", optional binding is another. – There is no way around it: If you want to do serious programming in Swift then you have to fully understand what optional are and how the work. It is covered in the official Swift documentation and also in many Q&A here on SO.
Im gonna read into that, thank you :) Any tips on how to add the word data in front of my JSON? Since its required to use an Array or a Dictionary, i don't really have an idea. Thought that the name of the dictionary i use would be part of the object in my JSON i am converting the dictionary into.
@Raijen: Well then you have to create a dictionary [ "data" : params ] and convert that to JSON.
Thanks again, that did very well! I have created a Dictionary<String,<Dictionary<String, String>>, and now everything is working fine :) Thank you for being so patient with me :)
0

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()

3 Comments

That's a good library, but irrelevant to this question, which is about creating JSON, not reading it.
I've updated an explanation on how to read and write JSON. It is good enough to read JSON, right?
Nice tip, a really good libary :) Even though getting through JSON Serialization has improved my coding skills concerning Swift, so i would recommend other starters to work their way through this itch, because its a very helpful lesson.

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.