Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
126 views
in Technique[技术] by (71.8m points)

c# - JsonSerializerSettings and Asp.Net Core

Trying to set JsonOutputFormatter options:

var jsonFormatter = (JsonOutputFormatter) options.OutputFormatters.FirstOrDefault(f => f is JsonOutputFormatter);
if (jsonFormatter != null)
{
    jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}

or

mvcBuilder.AddJsonOptions(jsonOptions =>
    {
        jsonOptions.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    });

But as soon as I add this, I get:

MissingMethodException: Method not found: 'Newtonsoft.Json.JsonSerializerSettings Microsoft.AspNet.Mvc.Formatters.JsonOutputFormatter.get_SerializerSettings()'.

I'm using the standard Microsoft.AspNet.Mvc.Formatters.Json (6.0.0-rc1-final)

Edit: Solved it by installing Newtonsoft.Json 6.0.6 (which downgrades all other references)

Anyone got that already? Thanks..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

.Net Core 1.0 RTM comes with CamelCase formatting out-of-the-box. This is a behavior change from RC2. However, if you need to modify it, try this snippet:

services.AddMvc()
        .AddJsonOptions(opt =>
    {
        var resolver  = opt.SerializerSettings.ContractResolver;
        if (resolver != null)
        {
            var res = resolver as DefaultContractResolver;
            res.NamingStrategy = null;  // <<!-- this removes the camelcasing
        }
    });

More information here.

For dotnet core 1.0.1:

  services
            .AddMvcCore()
            .AddJsonFormatters(o => o...);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...