json - 如何为 JSON 生成过滤字符串

标签 json swift

是否有任何约定可以为我在 Swift 中使用的对象生成过滤文本?

class Account {
  var active : Bool!
  ...
}

示例:我在 Swift 中有帐户类,在环回中有帐户模型,我想获得字段为“active = true”的帐户 我需要生成的过滤器是 = {"where": {"active": true}}

我需要手动输入这些类型的查询。我敢肯定有人想到了一种方法,我只需要关键字。

PS:我从 Realm 和 ObjectMapper 扩展了我的类。

最佳答案

更新的答案

如果我理解您在我原来的回答下的评论,您需要生成一个 JSON String,格式为 {"where": {"active": true}} 其中 true 实际上是您的 Account 实例的 bool 值。然后,此 JSON 字符串将用作 MongoDB 的查询/过滤器。

为此,我建议您向 Account 类添加一个计算属性。此属性将使用 NSJSONSerialization 从 bool 创建 JSON data,并使用 String() 创建 JSON String 来自这个数据。

例子:

class Account {
    var active : Bool!

    var boolQuery: String? {
        let dict = ["where": ["active": active]]
        if let json = try? NSJSONSerialization.dataWithJSONObject(dict, options: []),
                query = String(data: json, encoding: NSUTF8StringEncoding) {
            return query
        }
        return nil
    }
}

用法:

let acc = Account()
acc.active = true
if let query = acc.boolQuery {
    print(query)
}

打印:

{"where":{"active":true}}

let acc = Account()
acc.active = false
if let query = acc.boolQuery {
    print(query)
}

打印:

{"where":{"active":false}}

我不确定我是否在您的设置中得到了“谁做什么”(哪个类负责什么),但在我看来,这就是您需要的代码类型。

当然也可以是免费函数:

func boolQuery(account: Account) -> String? {
    let dict = ["where": ["active": account.active]]
    if let json = try? NSJSONSerialization.dataWithJSONObject(dict, options: []),
        query = String(data: json, encoding: NSUTF8StringEncoding) {
        return query
    }
    return nil
}

等等


上一个回答

你的问题有点不清楚,我不确定你所说的“我需要手动输入这些类型的查询”是什么意思......但我想,无论如何,你有一组 Account 实例。

然后很容易过滤这个数组,只获取activetrue的实例:

let result = arrayOfAccounts.filter { $0.active }

此处 result 是一个数组,仅包含 active 为 true 的帐户。

关于json - 如何为 JSON 生成过滤字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36533213/

相关文章:

javascript - 更改嵌套 JSON 的结构

javascript - 一旦文本从一个 UL 移动到另一个 UL,就禁用文本

java - 以 '/' 字符作为 JSON 键的 Jackson ObjectMapper

javascript - 无法获取从 PHP 到 $.ajax 的 JSON 回显

ios - 将用户交互锁定到 WKWebView

c# - 在 Monotouch 中将 IEnumerable<T> 简单转换为 JSON

ios - 获取文档文件夹中的文件列表

ios - 从 UIView 捕获 UIImage 然后在 WatchKit WKInterfaceImage 中使用它

ios - 自定义 UITableviewCells 正确显示,但该部分中只有一个是正确的类

ios - arm64 iOS Swift Gstreamer 库不支持 rtspsrc (Xcode 10.1)