我知道這個問題已經出現了很多,但是我一直在尋找答案,并沒有真正找到適合我的問題,因此我向您尋求幫助:
我有一個自定義類 [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, one rror); // 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>
我收到以下錯誤:
Blockquote JsonSerializationException:找不到用于型別加載的建構式。一個類應該有一個默認建構式、一個帶引數的建構式或一個標有 JsonConstructor 屬性的建構式。路徑“[0].name”,第 1 行,位置 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 上的教程
我正在使用 Visual Studio 在 Mac 上進行統一編碼。
感謝您的幫助。
uj5u.com熱心網友回復:
例外訊息是自我解釋的。您沒有類 Loadout 的默認建構式。因此,在您的 Loadout 類中,您需要添加
Loadout() {}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/463400.html
上一篇:洗掉嵌套在嵌套JSON檔案中
