我可以向Firebase Remote配置声明一个数组吗?

时间:2017-02-13 10:34:26

标签: android firebase firebase-remote-config

我是Android和Firebase的新手。 是否可以在Firebase远程配置的参数键内声明一个数组? enter image description here

我想为某些特定型号/移动设备提供一些促销活动。因此,如果我可以声明一系列模型(例如,三星J5,小米Note2等),我可以轻松地在这些模型上启用促销。 请帮帮我。

5 个答案:

答案 0 :(得分:11)

Firebase远程配置中的所有值最终都存储为字符串。布尔,数字等等都归结为字符串。当您要求其他类型时,SDK将解析该字符串值。

远程配置中没有“本机”数组。如果您想在Remote Config参数中使用一系列有序值,则应该以可以从字符串值(例如JSON或一些简单的分隔字符串)解析的方式表示它。

答案 1 :(得分:5)

Remote Config最近添加了通过将键值列表保存为JSON格式来保存键值列表的选项。

enter image description here

样品用量:

1.Json存储在远程配置中:

 [
      {
        "lesson": "1",
        "versionCode": 2
      },
      {
        "lesson": "2",
        "versionCode": 4
      },
      {
        "lesson": "3",
        "versionCode": 1
      }
    ]
  1. 科特林模型

    数据类Lesson(         val课程:Int,         val versionCode:Int )

3。检索json

String object = FirebaseRemoteConfig.getInstance().getString("test_json");
Gson gson = new GsonBuilder().create();
List<Lesson> lessons = gson.fromJson(object, new TypeToken<List<Lesson>>(){}.getType());

答案 2 :(得分:4)

Doug's回答相同,但有代码。

这是在斯威夫特,但你仍然应该得到漂移。

对于数组,请使用分隔的字符串,例如

"iron,wood,gold"并使用.components(separatedBy: ",")

将其拆分为字符串数组

对于词典,请使用“双重”分隔的字符串,例如

"iron:50, wood:100, gold:2000"

使用

将其转换为字典
    var actualDictionary = [String: Int]()

    // Don't forget the space after the comma
    dictionaryString.components(separatedBy: ", ").forEach({ (entry) in
    let keyValueArray = entry.components(separatedBy: ":")
            return actualDictionary[keyValueArray[0]] = Int(keyValueArray[1])
    })

    return actualDictionary

答案 3 :(得分:1)

我喜欢N Kuria's的答案,但这要求json中的空格必须准确。如果您想要一些更多的容错功能,以下是通过JSONSerialization以int数组形式读取的代码。

假设您的json中有以下整数数组:

 {
     "array": [1, 5, 4, 3]
 }
func getArray() -> [Int] {

    let jsonString = "{\"array\": [1, 5, 4, 3]}"
    let array = [Int]()

    guard let data = jsonString.data(using: .utf8) else { return array }
    if let json = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers) {
        guard let theArray = json as? [String: [Int]] else { return array }
        return theArray.first?.value ?? array

        // If you were reading in objects instead of ints, you would do
        // for (key, value) in theArray { /* append values to array */ }
    }

    return array
}

或者,如果您正在读取类类型的值,则可以枚举字典并在每次迭代时追加到数组中。 (请参阅第一个退货下方的评论。)

答案 4 :(得分:-1)

我还建议使用JSON - 因为在解析JSON时可以进行某种错误检测。通过拆分,您永远不会知道是否会产生正确的数组。