-2

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.

CosmicSeizure
  • 1,375
  • 5
  • 17
  • 35

2 Answers2

1

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
Serge
  • 40,935
  • 4
  • 18
  • 45
0

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);
Iggy
  • 4,767
  • 5
  • 23
  • 34
  • `-NBDmMEcFMNkPynkW3tG` would not be a [valid name for a member](https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/coding-style/identifier-names) in `c#` ... besides I am pretty sure that since this is the UserID it is a dynmic value you do not know beforehand => you can't hardcode it into you types ... and the given JSON is no array so it is no use to try and deserialize it into one ;) – derHugo Sep 07 '22 at 06:49