【发布时间】:2019-11-15 09:41:35
【问题描述】:
我从 Car 类型生成 JSON 表示,然后从该 json 创建一个 System.Object。当我尝试将该对象显式转换为 Car 类型时,它会显示错误“InvalidCastException:指定的转换无效”。谁能给我解释一下原因?
using System;
using UnityEngine;
[Serializable]
class Car
{
public string type;
}
public class Test : MonoBehaviour
{
void Start()
{
Car car = new Car();
car.type = "BMW";
string json = JsonUtility.ToJson(car);
System.Object @object = JsonUtility.FromJson<System.Object>(json);
car = (Car)@object;
Debug.Log(car.type);
}
}
【问题讨论】:
-
你正在反序列化到
object,它不能转换为Car。为什么不直接反序列化到Car?像这样:var car = JsonUtility.FromJson<Car>(json); -
我试图了解这个错误的深层原因。
-
原因是“你没有创建 Car 的实例,所以你不能强制转换为 Car”。