0

I am trying to deserialize this js object in Unity

{
   "1":{
      "id":1,
      "name":"John",
      "score":0,
      "character":0,
      "position":{
         "x":0,
         "y":1.069696307182312,
         "z":0
      }
   },
   "2":{
      "id":2,
      "name":"Matt",
      "score":0,
      "character":0,
      "position":{
         "x":0,
         "y":1.069696307182312,
         "z":0
      }
   }
}

I have tried a [Serializable] class with list inside and Dictionary inside:

    [Serializable]
    public class Players
    {
        public List<Player> players;
    }

    [Serializable]
    public class DictPlayers
    {
        public Dictionary<string,Player> players;
    }

    [Serializable]
    public class Player
    {
        public string name;
        public int score;
        public int character;
        public int id;
        public Vector3 position;
    }

These come up just as empty lists:

 public Players networkPlayers;
 public DictPlayers testNestedDict;

 testNestedDict = JsonUtility.FromJson<DictPlayers>(payload);
                
 networkPlayers = JsonUtility.FromJson<Players>(payload);

Any new ideas? Tried with Newtonsoft json also. Json stringify and just sending plain obj result the same.

  • 2
    Does this answer your question? [How can I deserialize JSON to a simple Dictionary in ASP.NET?](https://stackoverflow.com/questions/1207731/how-can-i-deserialize-json-to-a-simple-dictionarystring-string-in-asp-net). Specially `System.Web.Script.Serialization.JavaScriptSerializer` – TEEBQNE Sep 27 '21 at 18:28
  • Funny I also just had this problem, I had to deserialize the dictionary twice with Newtonsoft and it worked for me –  Sep 27 '21 at 18:47
  • 1
    @TEEBQNE as the [doc page](https://learn.microsoft.com/dotnet/api/system.web.script.serialization.javascriptserializer) mentions you should rather use either Newtonsoft .Net JSON or System.Text.Json ;) – derHugo Sep 27 '21 at 20:16
  • Besides the duplicate in general: Unity's built-in [Script Serialization](https://docs.unity3d.com/Manual/script-Serialization.html) (which the `JsonUtility` is using) doesn't support `Dictionary` .. as a simple rule: What you don't see in the Unity Inspector will not appear in a JSON / will not be loaded from a JSON => either way you need another library – derHugo Sep 27 '21 at 20:23

0 Answers0