我知道这个问题已经出现了很多次,但我一直在寻找答案,并不能真正找到一个适合我的,因此我请求你的帮助:
我有一个自定义类[Loadout]:
public class Loadout // used to save a players loadout on the server
{
public string name;
public float loadoutID;
public SO_Admiral admiral;
public FM_ShipSave[] shipsInTheLoadout;
public bool selectedLoadout;
public Loadout(string _name, FM_ShipSave[] _ShipSavesArray)
{
name = _name; // later this must come from an input-field
loadoutID = Random.Range(0f, 100000000f);
shipsInTheLoadout = _ShipSavesArray;
}
public Loadout(string _name)
{
name = _name;
shipsInTheLoadout = new FM_ShipSave[0];
}
}
还包括其他自定义类,如:
public class FM_ShipSave
{
// this class saves ID and position in the array of the ship
public int shipID;
public int tileX;
public int tileZ;
public FM_ShipSave(UnitScript _unit)
{
shipID = _unit.SO_ofThis.getPositioninAllUnitsArray();
tileX = _unit.getTileX;
tileZ = _unit.getTileZ;
}
}
,我将其序列化为. json文件,并将其发送到服务器并存储在那里。序列化部分工作得很好:
var request = new UpdateUserDataRequest // after what is supposed to happen with the current loadout is determined we upload it to the server
{
Data = new Dictionary<string, string> // create a new dicitonary
{
{"Loadouts", JsonConvert.SerializeObject(playerLoadouts)} // convert the List<Loadout> playerLoadouts into a .json file
}
};
PlayFabClientAPI.UpdateUserData(request, onDataSend, OnError); // then send it to the server, to be stored
链接到json编辑器的图片
但是当我试图对它进行反序列化时:
List<Loadout> playerLoadouts = JsonConvert.DeserializeObject<List<Loadout>>(_result.Data["Loadouts"].Value); // turn the jsonback into a List<Loadout>
我得到以下错误:
引用JsonSerializationException:无法找到用于类型Loadout的构造函数。一个类应该有一个默认构造函数,一个带参数的构造函数,或者一个带有JsonConstructor属性的构造函数。路径'[0].name',第一行,位置9.
我也试过用一个不同的更简单的类,那里一切都很好:
public class JsonTest
{
public string name;
public JsonTest(string _name)
{
name = _name;
}
}
发送:
// to test serialization
JsonTest _test = new JsonTest("test");
var request2 = new UpdateUserDataRequest // after what is supposed to happen with the current loadout is determined we upload it to the server
{
Data = new Dictionary<string, string> // create a new dicitonary
{
{"test", JsonConvert.SerializeObject(_test)} // convert the List<Loadout> playerLoadouts into a .json file
}
};
检索:public void testDeserialization(GetUserDataResult _result)
{
JsonTest _retrievedTest = JsonConvert.DeserializeObject<JsonTest>(_result.Data["test"].Value); // turn the jsonback into a List<Loadout>
Debug.Log("retrieved test deserialization name: " + _retrievedTest.name);
}
我因此得出结论,它与我的自定义类有关,但我不知道如何修复它。我应该编写自定义反序列化器吗?或者有没有别的解决办法?
我遵循这个教程来创建和上传json文件:链接到youtube上的教程
我在mac上使用visual studio编写unity。
谢谢你的帮助。
异常消息是自解释的。您没有类Loadout的默认构造函数。所以在Loadout类中你需要添加
Loadout() {}