我想要实现的目标。我有一个类,其中包含一些属性/对象。我只想使用我的自定义序列化器序列化那些满足CanConvert条件的对象,而其他对象则应默认处理。

问题在于,使用[JsonConverter(typeof(UnityObjectConverter))]可以正确序列化,但是反序列化失败。可能是因为我只保存了对象的路径,而不是整个对象的路径,并且当发生一些内部检查(我不知道为什么)时,它失败并返回null,因为从未调用ReadJson

使用“设置”时,它会解决更多问题,因为它不会序列化其余部分。我不想对整个类进行序列化,因为那样的话它就不会很通用,因为有几个对象继承了该类。类本身不是抽象的,因此可能有一些对象仅使用该类。如果有人可以帮助我,我将非常高兴。谢谢

 public class UnityObjectConverter : JsonConverter {

public override bool CanConvert(Type objectType) {
    Debug.Log(objectType.BaseType == typeof(UnityEngine.Object));
    return objectType.BaseType == typeof(UnityEngine.Object);
}

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
    Debug.Log("read");
    return UnityEditor.AssetDatabase.LoadAssetAtPath(reader.ReadAsString(), objectType);
}

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {
    Debug.Log("write");
    var item = (UnityEngine.Object)value;
    writer.WriteValue(UnityEditor.AssetDatabase.GetAssetPath(item));
    writer.Flush();
}

public override bool CanRead {
    get {
        return true;
    }
}

public override bool CanWrite {
    get {
        return true;
    }
}
 }

属性示例
 /// <summary>
    /// GameObject if item is needed to be visualised
    /// </summary>
    [JsonConverter(typeof(UnityObjectConverter))]
    public GameObject gameObject { get { return _gameObject; } private set { _gameObject = value; } }
    protected GameObject _gameObject = null;

反序列化的示例
public static void Add(Item i) {
        items.Add(i);
        if (!System.IO.File.Exists(Application.dataPath + DATA_PATH))
            System.IO.File.Create(Application.dataPath + DATA_PATH).Close();
        using (System.IO.StreamWriter sw = System.IO.File.CreateText(Application.dataPath + DATA_PATH)) {
            sw.Write(JsonConvert.SerializeObject(items));
        }
    }

static void Load() {
        items.Clear();
        Item[] it = JsonConvert.DeserializeObject<Item[]>(System.IO.File.ReadAllText(Application.dataPath + DATA_PATH));
        if (it != null)
            items.AddRange(it);
    }

最佳答案

当我做这种事情时,我创建了一个JsonSerializerSettings对象

 var settings = new JsonSerializerSettings
 {
     ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
     DefaultValueHandling = DefaultValueHandling.Ignore,
     NullValueHandling = NullValueHandling.Ignore
 };
 settings.Converters.Add(new Converter());

然后将其传递给解串器
 var json = textReader.ReadToEnd();
 return JsonConvert.DeserializeObject<T>(json, settings);

10-08 16:21