您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

JSON.net:如何在不使用默认构造函数的情况下反序列化?

JSON.net:如何在不使用默认构造函数的情况下反序列化?

如果有一个对象,Json.Net倾向于在对象上使用认的(无参数)构造函数。如果存在多个构造函数,并且您希望Json.Net使用非[JsonConstructor]构造函数,则可以将属性添加到希望Json.Net调用的构造函数中。

[JsonConstructor]
public Result(int? code, string format, Dictionary<string, string> details = null)
{
    ...
}

重要的是,构造函数参数名称必须与JSON对象的相应属性名称匹配(忽略大小写),才能正常工作。但是,不必一定要为对象的每个属性都具有构造函数参数。对于那些构造函数参数未涵盖的JSON对象属性,Json.Net将[JsonProperty]在构造对象后尝试使用公共属性访问器(或标有的属性/字段)填充对象。

如果您不想在类中添加属性,或者不希望控制试图反序列化的类的源代码,那么另一种选择是创建一个自定义JsonConverter来实例化并填充您的对象。例如:

class ResultConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(Result));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        // Load the JSON for the Result into a JObject
        JObject jo = JObject.Load(reader);

        // Read the properties which will be used as constructor parameters
        int? code = (int?)jo["Code"];
        string format = (string)jo["Format"];

        // Construct the Result object using the non-default constructor
        Result result = new Result(code, format);

        // (If anything else needs to be populated on the result object, do that here)

        // Return the result
        return result;
    }

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

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

然后,将转换器添加到序列化程序设置中,并在反序列化时使用这些设置:

JsonSerializerSettings settings = new JsonSerializerSettings();
settings.Converters.Add(new ResultConverter());
Result result = JsonConvert.DeserializeObject<Result>(jsontext, settings);
dotnet 2022/1/1 18:15:30 有526人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶