没有调用ReadJson

时间:2015-06-16 12:12:32

标签: c# unity3d json.net

我想要实现的目标。我有一个类中有一些属性/对象。我想使用我的自定义序列化程序仅序列化那些符合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);
    }

1 个答案:

答案 0 :(得分:1)

当我做这种事时,我创建了一个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);