c# - Json.NET 自定义 JsonConverter 被忽略

标签 c# asp.net-mvc json json.net

我有一个泛型类,我想用它的一个属性的值序列化它的子类。

为此,我写了一个自定义JsonConverter并使用 JsonConverter(Type) 将其附加到基类属性 - 但是,它似乎从未被调用过。作为引用,如下例所示,我正在序列化一个 List<>使用 System.Web.Mvc.Controller.Json() 的对象方法。

如果有实现相同结果的完全更好的方法,我绝对愿意接受建议。

示例

查看函数

public JsonResult SomeView()
{
    List<Foo> foos = GetAListOfFoos();
    return Json(foos);
}

自定义 JsonConverter

class FooConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        System.Diagnostics.Debug.WriteLine("This never seems to be run");
        // This probably won't work - I have been unable to test it due to mentioned issues.
        serializer.Serialize(writer, (value as FooBase<dynamic, dynamic>).attribute);
    }

    public override void ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override bool CanConvert(Type objectType)
    {
        System.Diagnostics.Debug.WriteLine("This never seems to be run either");
        return objectType.IsGenericType
            && objectType.GetGenericTypeDefinition() == typeof(FooBase<,>);
    }
}

Foo 基类

[JsonConverter(typeof(FooConverter))]
public abstract class FooBase<TBar, TBaz>
    where TBar : class
    where TBaz : class
{
    public TBar attribute;
}

Foo 实现

public class Foo : FooBase<Bar, Baz>
{
    // ...
}

当前输出

[
    {"attribute": { ... } },
    {"attribute": { ... } },
    {"attribute": { ... } },
    ...
]

期望的输出

[
    { ... },
    { ... },
    { ... },
    ...
]

最佳答案

发生在我身上的是,我按照 Visual Studio 的建议自动添加了 using 语句。并错误地添加了 using System.Text.Json.Serialization; 而不是 using Newtonsoft.Json;

所以我在目标类上使用了 System.Text.Json.Serialization.JsonConverterAttribute。 Json.Net(正确地)忽略了它。

关于c# - Json.NET 自定义 JsonConverter 被忽略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25324912/

相关文章:

c# - 什么时候用 'if…else if'什么时候用

c# - 使用正确的编码导出文件

c# - SizeToContent 绘制不需要的边框

c# - Office 365 客户端 API SendMailAsync 返回未经授权

xcode - cocoa - 应用程序架构

javascript - 将包含属性的 Backbone 集合序列化为 JSON

c# - 是否可以创建一个包含多页 tiff 文件所有帧的 base64 字符串?

javascript - 如何防止用户向按钮发送垃圾邮件?

asp.net-mvc - ASP.NET MVC 中的动态(运行时生成)表单

android - 解析数据时出错 - 字符串无法转换为 JSONObject