JSONSerialization选项有什么作用以及它们如何更改jsonResult? [英] What do JSONSerialization options do and how do they change jsonResult?
问题描述
我在项目中经常使用 JSONSerialization
。
以下是我的 JSONSerialization
代码的示例:
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?
我发现的选项:
NSJSONReadingMutableContainers:
指定将数组和字典创建为可变对象。
Specifies that arrays and dictionaries are created as mutable objects.
NSJSONReadingMutableLeaves:
指定JSON对象图中的叶字符串是创建为
NSMutableString实例。
Specifies that leaf strings in the JSON object graph are created as instances of NSMutableString.
NSJSONReadingAllowFragments:
指定解析器应该允许非
的顶级对象作为NSArray或NSDictionary的实例。
Specifies that the parser should allow top-level objects that are not an instance of NSArray or NSDictionary.
Note2 :我在以下网址找到了这些定义: https://developer.apple.com/reference/foundation/nsjsonreadingoptions
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 :).
任何帮助表示赞赏。
谢谢。
推荐答案
前两个选项的简短回答:
Short answer for the first two options:
在Swift中忽略它们!
在Swift中,您可以使用 var
关键字使对象变为可变。
In Swift you can make objects mutable just with the var
keyword.
目标-C另一方面,你需要选项来制作集合类型
NSArray
/ NSDictionary
mutable - > NSMutableArray
/ NSMutableDictionary
,带有 NSJSONReadingMutableContainers
选项或值字符串 - > NSMutableString
带 NSJSONReadingMutableLeaves
。
In Objective-C on the other hand you need the options to make the collection types
NSArray
/ NSDictionary
mutable -> NSMutableArray
/ NSMutableDictionary
with the NSJSONReadingMutableContainers
option or the value strings -> NSMutableString
with NSJSONReadingMutableLeaves
.
在Objective-C和Swift中,如果你只是正在阅读 JSON y你根本不需要可变性。
In both Objective-C and Swift if you are only reading the JSON you don't need mutability at all.
NSJSONReadingAllowFragments
如果收到的JSON的根对象是不数组或字典。如果是数组或字典,您也可以省略该选项。
NSJSONReadingAllowFragments
is important if the root object of the received JSON is not an array or a dictionary. If it is an array or dictionary you can omit that option, too.
一对空括号 []
表示没有选项
( options
可以在Swift 3中省略。)
The pair of empty brackets []
represents No options
(options
can be omitted in Swift 3).
这篇关于JSONSerialization选项有什么作用以及它们如何更改jsonResult?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!