Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

ios - What do JSONSerialization options do and how do they change jsonResult?

I am using JSONSerialization quite often in my project. Here is an example of my JSONSerialization code:

let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: Any] 

Note: Options are missing for purpose and I normally have them in my project.

My problem is that I am not pretty sure what do these options: [] do?

What I have found about options:

NSJSONReadingMutableContainers:

Specifies that arrays and dictionaries are created as mutable objects.

NSJSONReadingMutableLeaves:

Specifies that leaf strings in the JSON object graph are created as instances of NSMutableString.

NSJSONReadingAllowFragments:

Specifies that the parser should allow top-level objects that are not an instance of NSArray or NSDictionary.

Note2: I found those definitions on : https://developer.apple.com/reference/foundation/nsjsonreadingoptions

My question is: Can someone please explain me differences between those options , what should I use them for and if you could show me some code example of those options it would be perfect :).

Any help appreciated.

Thanks.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Short answer for the first two options:

Ignore them in Swift!

In Swift you can make objects mutable just with the var keyword.

In Objective-C on the other hand you need

  • NSJSONReadingMutableContainers to make the nested collection types mutable NSArrayNSMutableArray and NSDictionaryNSMutableDictionary.
  • NSJSONReadingMutableLeaves to make the value strings mutable → NSMutableString.

In both Objective-C and Swift if you are only reading the JSON you don't need mutability at all.

The third option NSJSONReadingAllowFragments is important if the root object of the received JSON is not an array and not a dictionary.
If it is an array or dictionary you can omit that option, too.

The pair of empty brackets [] represents No options (the options parameter can be omitted in Swift 3+).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...