在 Objective-C 中解析 JSON 的首选数据类型是什么?

发布于 2025-01-08 20:54:52 字数 95 浏览 0 评论 0原文

在 Objective-C 中解析 JSON 的首选数据类型是什么?我正在寻找一种能够反映使用 key=>value 样式和数组形式的数据类型。

What is the preferred datatype to parse JSON into in Objective-C? I'm looking for a data type that mirrors the ability to use key=>value style and just array form.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

北风几吹夏 2025-01-15 20:54:52

通常,库(例如 SBJson)会将其解析结果作为 NSArray 或 NSDictionary,仅取决于解析的 JSON 元素是对象还是数组。

来自SBJsonParser.h

/**
 @brief Return the object represented by the given string

 This method converts its input to an NSData object containing UTF8 and calls -objectWithData: with it.

 @return The NSArray or NSDictionary represented by the object, or nil if an error occured.
 */
- (id)objectWithString:(NSString *)repr;

在您的问题中,您问< em>“我正在寻找一种能够反映使用 key=>value 的能力的数据类型”,根据定义,这正是字典......所以,您可能正在寻找NSDictionary

Typically libraries (such as SBJson) will return their parsed results as either an NSArray or an NSDictionary, just depending on if the parsed JSON element was an object or an array.

From SBJsonParser.h:

/**
 @brief Return the object represented by the given string

 This method converts its input to an NSData object containing UTF8 and calls -objectWithData: with it.

 @return The NSArray or NSDictionary represented by the object, or nil if an error occured.
 */
- (id)objectWithString:(NSString *)repr;

In your question you asked "I'm looking for a data type that mirrors the ability to use key=>value", that is by definition exactly what a dictionary is... so, you're probably looking for NSDictionary.

你爱我像她 2025-01-15 20:54:52

这个问题没有任何意义。 JSON 字符串本身决定反序列化时您将获得的对象类型。它可以是字符串、数字、数组或字典。您必须准备好接受其中任何一个。如果您使用 NSJSONSerialization,您会注意到解码方法返回 id,这意味着您事先不知道类型。您必须使用 isKindOfClass: 来确定您实际返回的内容。

The question doesn't make any sense. The JSON string itself determines what type of object you are going to get when it's deserialized. It can be a string, number, array or dictionary. You have to be prepared to receive any of those. If you use NSJSONSerialization, you'll notice that the decoding methods return id, which means you don't know the type ahead of time. You will have to use isKindOfClass: to figure out what you actually got back.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文