JSONSerialization 选项有什么作用以及它们如何改变 jsonResult? [英] What do JSONSerialization options do and how do they change jsonResult?

查看:22
本文介绍了JSONSerialization 选项有什么作用以及它们如何改变 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.

我的问题是我不太确定这些 options: [] 有什么作用?

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.

另一方面,在Objective-C中你需要

In Objective-C on the other hand you need

  • NSJSONReadingMutableContainers 使嵌套的集合类型可变 NSArrayNSMutableArrayNSDictionaryNSMutableDictionary.
  • NSJSONReadingMutableLeaves 使值字符串可变 → NSMutableString.
  • NSJSONReadingMutableContainers to make the nested collection types mutable NSArrayNSMutableArray and NSDictionaryNSMutableDictionary.
  • NSJSONReadingMutableLeaves to make the value strings mutable → NSMutableString.

在 Objective-C 和 Swift 中,如果您只阅读 JSON,则根本不需要可变性.

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

第三个选项 NSJSONReadingAllowFragments 很重要,如果接收到的 JSON 的根对象不是一个数组并且不是一个字典.
如果它一个数组或字典,你也可以省略该选项.

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.

一对空括号[]代表No options(options参数在Swift 3+中可以省略).

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

这篇关于JSONSerialization 选项有什么作用以及它们如何改变 jsonResult?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆