I am developing a game which has a class called UserInfo
.
Inside the UserInfo
class there is a public List<Lineup> lineups
variable.
And Lineup
contains public Dictionary<Vector2Int, Collection> cardLocations
.
My problem is, JsonConvert.SerializeObject
does correctly produce the result I want, but when I do JsonConvert.DeserializeObject<UserInfo>
, Vector2Int
remains to be a string like "(x, y)"
.
How should I fix it?
I wrote a JsonConverter
to convert it, and used
JsonConvert.SerializeObject(userInfo, Formatting.Indented, new Vec2Converter())
for serialization and
JsonConvert.DeserializeObject<UserInfo>(json, new Vec2Converter())
to deserialization, but it doesn't work.
Here is my JsonConverter
script:
using Newtonsoft.Json;
using UnityEngine;
using System;
public class Vec2Converter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(value.ToString());
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var vector2Int = serializer.Deserialize<Vector2Int>(reader);
Debug.Log(vector2Int);
return vector2Int;
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(Vector2Int);
}
}
Another weird thing is that, when I tried to change Vector2Int
to other data structure like Lineup
or Dictionary<Vector2Int, Collection>
, Unity exited when I clicked play. After I changed it back, it became ok. The ok means it's not exiting but still giving me the error message.
Forgot to put the error message: ArgumentException: Could not cast or convert from System.String to UnityEngine.Vector2Int
Here are the classes.
public class UserInfo {
public string username;
public int playerID;
public List<Collection> collection = new List<Collection>();
public List<Lineup> lineups = new List<Lineup>(); // Here is the problem
public Dictionary<string, int> contracts = new Dictionary<string, int>();
public int coins = 0;
public int rank = 0;
public int lastLineupSelected = -1;
public int winsToday = 0;
public Stats total = new Stats();
public Dictionary<string, Stats> boardResults = new Dictionary<string, Stats>();
public List<Mission> missions;
public string preferredBoard = "Standard Board";
public string lastModeSelected = "";
public int gameID;
public bool missionSwitched = false;
}
public class Lineup
{
public Dictionary<Vector2Int, Collection> cardLocations; // Here is the problem
public List<Tactic> tactics;
public string boardName;
public string lineupName;
public string general;
public bool complete;
}
public class Collection
{
public string name = "";
public string type = "";
public int count = 1;
public int health = 0;
public int oreCost = 0;
}