Hopefully I’m missing something simple here, but I can’t seem to figure this out.
I’m refactoring my database in Firebase to align more with the best practices found here.
The key problem I’m trying to solve specifically deals with removing elements from an array, but since they recommend against arrays, I’m trying to figure out the proper work around.
So I tap my database, and get the following json string:
Now, I want to generate an array from each of the keys found inside of the “data” object. Each time I pull this data the number of keys fluctuates.
Following the firebase database setup of objects instead of arrays, each time I add new element of data, it adds a new key to the data object. I ultimately get why they want the data like this,but I’m struggling to piece it all back together in Unity.
Once I get the array generated from the string I can map it back to my particular class and all will be well, I just can’t figure out how to do this string-to-json conversion so I can then map over the keys and generate the array.
A string can be JSON. What you have up there appears to be somewhat-valid JSON.
You can use jsonlint.com to verify if the JSON is valid.
You can use json2csharp.com to create data containers to hold it.
You can use the built-in Unity JSON utility to deserialize it but it is EXTREMELY limited and won’t work unless a whole host of tight restrictions are obeyed strictly.
Instead, I recommend installing NewtonSoft JSON .NET, package available free on the Unity Asset Store, as it is far more flexible and feature-full…
Once it is in a data structure you can change it however you like.
Just in case anyone comes across this thread in the future, here is how I was able to solve my problem.
Install the NewtonSoft JSON.NET package mentioned above.
And then de-serialize the incoming JSON like so:
// webRequest contains my fetched data
var dataByKey = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, MyDataClass>>(webRequest.downloadHandler.text);
// create my new list
List<MyDataClass> dataList = new List<MyDataClass>();
// add all of the values from my keys into the new list
dataList.AddRange(dataByKey.Values.ToList());
// now do what you want with the data
Basically, I knew the class structure of my underlying data coming in, but the fact that it was buried inside of keys, instead of simply as elements in an array, proved challenging. I knew how to do this type of thing in javascript, but wasn’t sure of the process in C#.
The Free Plugin was 100% helpful in turning a pseudo random json string into a workable object.