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
1.6k views
in Technique[技术] by (71.8m points)

swift - Ordered Dictionary in JSON

There are 3 string variables

public var userLoginId : String?
public var searchString : String?
public var tableName : String?

I have a dictionary:

let dict = ["userLoginId" : userLoginId, "searchString" : searchString,"tableName" : tableName]

Now I serialize it by JSON:

let data =  try! JSONSerialization.data(withJSONObject: dict, options :[])
let jsonstring = String(data:data, encoding:.utf8)!

In jsonstring, every time I get an unordered JSON like below:

"{"tableName":"null","userLoginId":"Dilip","searchString":"Tata"}"

How can I get in the same format in which I assigned value to dictionary?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Dictionaries are unordered

??But !

Since JSON is a String you can have an ordered JSON. You can use this library to parse the JSON in the original order. The usage is simple:

try JSON.parse(string: jsonString)

Sorted Dictionary

From iOS 11 and macOS 10.13 there is a new option for JSONSerialization for sorting keys that you can use:

JSONSerialization.data(withJSONObject: json, options: [.sortedKeys])

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

...