Can I declare an array to Firebase Remote config?
I like N Kuria's answer, but that requires the whitespace in your json to be exact. If you want something a little more fault tolerant, here is code to read in an array of ints via JSONSerialization.
Let's say you had this array of ints in your 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
}
Alternatively, if you were reading in values of a class type, you could just enumerate the dictionary and append to an array with each iteration. (See the comment beneath the first return.)
All of the values in Firebase Remote Config are ultimately stored as strings. Booleans, numbers, etc, are all boiled down to strings. The SDK will just parse that string value when you ask for as some other type.
There are no "native" arrays in Remote Config. If you want a series of ordered values in a Remote Config parameter, you should represent it in a way that can be parsed from the string value (such as JSON or some simple delimited strings).
Same as Doug's answer, but with code.
This is in Swift, but you should still get the drift.
For arrays, use a delimited string e.g.
"iron,wood,gold"
and split it into an array of string using .components(separatedBy: ",")
For dictionaries, use a "doubly" delimited string e.g.
"iron:50, wood:100, gold:2000"
convert it into a dictionary using
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
The Remote Config has recently added the option to save a key-value list by saving it to a JSON format.
Sample usage:
1.Json stored in Remote Configs:
[
{
"lesson": "1",
"versionCode": 2
},
{
"lesson": "2",
"versionCode": 4
},
{
"lesson": "3",
"versionCode": 1
}
]
2.Kotlin model
data class Lesson(val lesson: Int, val versionCode: Int)
3.Retrieve json
String object = FirebaseRemoteConfig.getInstance().getString("test_json");
Gson gson = new GsonBuilder().create();
List<Lesson> lessons = gson.fromJson(object, new TypeToken<List<Lesson>>(){}.getType());