Home > OS >  How to deserialize JSON object from Firebase
How to deserialize JSON object from Firebase

Time:09-07

i have this list of users and I have a bit hard time to figure out how to deserialize it in C#

{"-NBDmMEcFMNkPynkW3tG":{"userID":"-NBDmMEcFMNkPynkW3tG"},"-NBDmO1uKeY22QD5H5DJ":{"userID":"-NBDmO1uKeY22QD5H5DJ"}}

I am using Unity JsonUtility and JsonHelper, but no models i tried to define provide any results.

Thanks for any help.

CodePudding user response:

I highly recommend you to google and install Newtonsoft.Json for Unity3d

using Newtonsoft.Json;

var jsonParsed=JObject.Parse(json);
    
List<string> userIDs=jsonParsed.Properties().Select(p=> (string) p.Value["userID"]).ToList();

userIDs

    -NBDmMEcFMNkPynkW3tG
    -NBDmO1uKeY22QD5H5DJ

CodePudding user response:

You have to make sure to add the Serializable attributes to the model classes. Apart from that the models are illegal as the variables start with a dash.

[Serializable]
public class Model {
    public UserModel -NBDmMEcFMNkPynkW3tG;
    public UserModel -NBDmO1uKeY22QD5H5DJ;
}

[Serializable]
public class UserModel {
    public string userID;
}

var json = "{\"-NBDmMEcFMNkPynkW3tG\":{\"userID\":\"-NBDmMEcFMNkPynkW3tG\"},\"-NBDmO1uKeY22QD5H5DJ\":{\"userID\":\"-NBDmO1uKeY22QD5H5DJ\"}}";
var model = JsonUtility.FromJson<Model>(json);
Debug.Log(model.-NBDmMEcFMNkPynkW3tG.userID);

You could consider using an array instead.

[Serializable]
public class Model2 {
    public UserModel[] users;
}

var json2 = "{\"users\":[{\"userID\":\"-NBDmMEcFMNkPynkW3tG\"},{\"userID\":\"-NBDmO1uKeY22QD5H5DJ\"}]}";
var model2 = JsonUtility.FromJson<Model2>(json2);
foreach (var user in model2.users) Debug.Log(user.userID);
  • Related