如何使用扩展类中的默认构造函数使JSON.NET反序列化?

时间:2017-08-10 15:51:13

标签: c# json serialization

我正在尝试反序列化扩展类中的对象,但它并不像我期望的那样工作。我已经读过我可以使用JsonSerializerSettings让JSON反序列化器使用私有构造函数。但由于某种原因,JsonSerializerSettings对我不起作用。这是我正在使用的JSON读写器:

public class FileStorageService<T> : IStorageService<T> where T : IEquatable<T>

    /// <summary>
    /// Writes the given object instance to a JSON file.
    /// Source: https://stackoverflow.com/questions/6201529/turn-c-sharp-object-into-a-json-string-in-net-4
    /// </summary>
    /// <param name="filePath">The file path to write the object instance to.</param>
    /// <param name="objectToWrite">The object instance to write to the file.</param>
    /// 
    /// Comment source: https://stackoverflow.com/questions/6115721/how-to-save-restore-serializable-object-to-from-file
    public void WriteJSONFile(string filePath, T objectToWrite)
    {
        string json = JsonConvert.SerializeObject(objectToWrite);
        File.WriteAllText(filePath, json);
    }

    /// <summary>
    /// Reads an object instance from a JSON file.
    /// </summary>
    /// <param name="filePath">The file path to read the object instance from.</param>
    /// <returns>Returns a new instance of the object read from the JSON file.</returns>
    /// 
    /// Comment source: https://stackoverflow.com/questions/6115721/how-to-save-restore-serializable-object-to-from-file
    public T ReadJSONFile(string filePath)
    {
        if (!File.Exists(filePath))
        {
            FileStream fs = new FileStream(filePath, FileMode.CreateNew);
            fs.Close();
        }
        JsonSerializerSettings settings = new JsonSerializerSettings
        {
            ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
        };
        string json = File.ReadAllText(filePath, Encoding.UTF8);
        return JsonConvert.DeserializeObject<T>(json, settings);
    }
}

这是我正在尝试读/写的课程的一个例子:

public class MyObject : IEquatable<MyObject>
{
    public string myString { get; set; }
    public byte[] myBytes { get; set; }

    protected MyHasher hasher;

    public MyObject(string first, string second)
    {
        this.myString = first;

        hasher = new MyHasher();
        this.myBytes = hasher.ComputeHash(second);
    }

    ... (implementing IEquatable below)
}

当我在Visual Studio中运行程序时,我得到一个空指针异常:

“Newtonsoft.Json.dll中发生了'System.ArgumentNullException'类型的未处理异常

附加信息:字符串引用未设置为String的实例。“

...使用调用堆栈指向hasher.ComputeHash(second)方法:

> this.myBytes = hasher.ComputeHash(second);
> return JsonConvert.DeserializeObject<T>(json, settings);

调试它,我发现JsonConvert.DeserializeObject正在调用MyObject的公共构造函数并给它空值(子问题:这怎么可能?),这是我不想要的。我希望它使用默认构造函数。

我可以添加: new()约束来强制对象拥有一个公共无参数构造函数,但我希望我的扩展类能够处理任何类型的对象(字符串,整数等),而不仅仅是自定义我创建的对象。

作为最终的并发症,请注意我无法以任何方式更改MyObject

我该怎么做?

0 个答案:

没有答案