Json.NET自定义JsonConverter被忽略

ack*_*ell 7 c# asp.net-mvc json json.net

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

为此,我编写了一个自定义JsonConverter并使用JsonConverter(Type)Attribute 将其附加到基类- 但是,它似乎永远不会被调用.作为参考,如下例所示,我List<>使用该System.Web.Mvc.Controller.Json()方法序列化一个对象.

如果有一个更好的方法来实现相同的结果,我绝对愿意接受建议.

查看功能

public JsonResult SomeView()
{
    List<Foo> foos = GetAListOfFoos();
    return Json(foos);
}
Run Code Online (Sandbox Code Playgroud)

自定义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<,>);
    }
}
Run Code Online (Sandbox Code Playgroud)

Foo基类

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

Foo实现

public class Foo : FooBase<Bar, Baz>
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)

电流输出

[
    {"attribute": { ... } },
    {"attribute": { ... } },
    {"attribute": { ... } },
    ...
]
Run Code Online (Sandbox Code Playgroud)

期望的输出

[
    { ... },
    { ... },
    { ... },
    ...
]
Run Code Online (Sandbox Code Playgroud)

Ted*_*olo 12

我遇到的情况是,我using按照 Visual Studio 的建议自动添加了该语句。并错误地添加using System.Text.Json.Serialization;而不是using Newtonsoft.Json;

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


yar*_*kan 7

首先,System.Web.Mvc.Controller.Json()不能与Json.NET一起使用 - 它使用的JavaScriptSerializer对你的Json.NET东西一无所知.如果你仍然想使用System.Web.Mvc.Controller.Json()调用,你应该做一些像这样.也改为WriteJson:

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
    serializer.Serialize(writer, ((dynamic)value).attribute);
}
Run Code Online (Sandbox Code Playgroud)

我认为这应该使你的代码工作.

  • ASP.NET WebApi使用JSON.NET作为json序列化程序,但ASP.NET MVC不使用.我知道这令人困惑. (4认同)