Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
512 views
in Technique[技术] by (71.8m points)

swift - Dictionary wrong order - JSON

I am trying to create a dictionary that I can make into a JSON formatted object and send to the server.

Example:

    var users = [
[
"First": "Albert", 
"Last": "Einstein", 
    "Address":[
        "Street": "112 Mercer Street",
        "City": "Princeton"]
],
[
"First": "Marie", 
"Last": "Curie", 
    "Address":[
        "Street": "108 boulevard Kellermann",
        "City": "Paris"]]
]

I use this function

func nsobjectToJSON(swiftObject: NSObject) -> NSString {
    var jsonCreationError: NSError?
    let jsonData: NSData = NSJSONSerialization.dataWithJSONObject(swiftObject, options: NSJSONWritingOptions.PrettyPrinted, error: &jsonCreationError)!
    var strJSON = NSString()

    if jsonCreationError != nil {
        println("Errors: (jsonCreationError)")
    }
    else {
        // everything is fine and we have our json stored as an NSData object. We can convert into NSString
        strJSON =  NSString(data: jsonData, encoding: NSUTF8StringEncoding)!
        println("(strJSON)")
    }
    return strJSON
}

But my result is this:

[
  {
    "First" : "Albert",
    "Address" : {
      "Street" : "112 Mercer Street",
      "City" : "Princeton"
    },
    "Last" : "Einstein"
  },
  {
    "First" : "Marie",
    "Address" : {
      "Street" : "108 boulevard Kellermann",
      "City" : "Paris"
    },
    "Last" : "Curie"
  }
]

Problem: why is the last name last? I think it should be above address. Please let me know what I am doing wrong with the NSDictionary for this to come out wrong. Any help would be very much appreciated - thank you.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To post what has already been said in comments: Dictionaries are "unordered collections". They do not have any order at all to their key/value pairs. Period.

If you want an ordered collection, use something other than a dictionary. (an array of single-item dictionaries is one way to do it.) You can also write code that loads a dictionary's keys into a mutable array, sorts the array, then uses the sorted array of keys to fetch key/value pairs in the desired order.

You could also create your own collection type that uses strings as indexes and keeps the items in sorted order. Swift makes that straightforward, although it would be computationally expensive.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...