0

I have a class like this:

using UnityEngine;

[System.Serializable]
public class PlayerInfo
{
  public string playerId;
  public string deviceId;

  public static PlayerInfo CreateFromJSON(string jsonString)
  {
    return JsonUtility.FromJson<PlayerInfo>(jsonString);
  }
}

And my client receives updates with a function like this:

void OnPlayerLocalJoin(Socket socket, Packet packet, params object[] args)
{
  Debug.Log(args[0]);
}

According to the documentation (which need more detail), the args should use the default json decoder, but I see it returns args as System.Object[], but oddly enough when I try args[0] my log returns:

System.Collections.Generic.Dictionary`2[System.String,System.Object]

When I print out the raw "packet" object, I do see my object:

[ "playerLocalUpdate", {"playerId":"abc","deviceId":"150B"} ]

No matter what I try, I cannot get the second part of this array to be a dictionary or better yet, how can I get it to be an instance of PlayerInfo

Debug.Log(packet.ToString());
var serialized = JsonUtility.ToJson(packet.ToString());
Debug.Log(serialized);

I'm trying to follow the docs: https://besthttp-documentation.readthedocs.io/en/latest/#3.%20Socket.IO/2%20Subscribing%20and%20receiving%20events/

JP Silvashy
  • 46,977
  • 48
  • 149
  • 227

1 Answers1

1

The easy bit is you want to do

PlayerInfo newPlayerInfo = PlayerInfo.CreateFromJSON(jsonString);

where jsonString is '{"playerId":"abc","deviceId":"150B"}'. We can see that from the Unity docs. I think you've worked that out already.

As you say, you can see this string arriving in your packet. As you also say, it's not clear from the HTTP/2 docs what args contains. Although the dictionary may be the string we want converted to a dictionary, which isn't much use to us. You could investigate further by casting args[0] to Dictionary<string, object> and then doing a foreach on it and logging the results. I'm also unclear what args[1] might contain?

Maybe it is best to get it out of the packet. My guess is that to get the jsonString you need to do something like:

var packetArray = JsonUtility.FromJson<object[]>(packet.ToString());
string jsonString = packetArray[1].ToString();

That's because packet is JSON and we want to convert FROM the JSON string (which represents an array) to a C# array. Then we want the second item in the array. I think. It's hard to be sure without access to the code.

Rich N
  • 8,939
  • 3
  • 26
  • 33