简体   繁体   中英

deserializing System.Collections.Generic.Dictionary

My API responds with with JSON as a string, when my Unity app receives this object, I'm unsure how to deserialize it into an object from it's type of System.Collections.Generic.Dictionary , I want to make it an object of my class: PlayerInfo which is serializable.

void OnPlayerLocalUpdate(Socket socket, Packet packet, params object[] args)
{
  var myObject = JsonUtility.FromJson<PlayerInfo>(args[0].ToString());

}

The above code raises:

JSON parse error: Invalid value.   at (wrapper managed-to-native) UnityEngine.JsonUtility.FromJsonInternal(string,object,System.Type) at UnityEngine.JsonUtility.FromJson (System.String json, System.Type type)

How do I deserialize that object?

void OnPlayerLocalUpdate(Socket socket, Packet packet, params object[] args)
{
  var serialized = JsonUtility.ToJson(args[0]);
  var myObject = JsonUtility.FromJson<PlayerInfo>(serialized);
}

First you need to serialize it then you deserialize it your expected object type. If args[0] is a Dictionary it should serialize to valid json object. Another way of achieving this is to initialize your PlayerInfo manually. Then use reflection to set its' properties.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM