Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c# - Add Multiple Contract Resolver in Newtonsoft.Json

Blueprint for data structure:

public class Movie
{
    public string Name { get; set; }
}

Using Newtonsoft.Json, I have the following configuration for Json serialization.

var settings = new JsonSerializerSettings() { 
    ContractResolver = new CamelCasePropertyNamesContractResolver(),
};

Clearly that, this will print out:

{
    name: null
}

Now, I need to add another NullToEmptyStringResolver to the ContractResolver in JsonSerializerSettings, how can I achieve that which output as below:

{
    name: ""
}
  • Please note that my NullToEmptyStringResolver is already written. But I need to add both NullToEmptyStringResolver and CamelCasePropertyNamesContractResolver to the Contract Resolver.
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Json.Net does not allow more than one contract resolver at a time, so you will need a way to combine their behaviors. I'm assuming that NullToEmptyStringResolver is a custom resolver which inherits from Json.Net's DefaultContractResolver class. If so, one simple way to achieve your desired result is to make the NullToEmptyStringResolver inherit from CamelCasePropertyNamesContractResolver instead.

public class NullToEmptyStringResolver : CamelCasePropertyNamesContractResolver
{
    ...
}

If you don't like that approach, another idea is to add the camel casing behavior to yourNullToEmptyStringResolver. If you take a look at how CamelCasePropertyNamesContractResolver is implemented in the source code, you'll see this is as simple as setting the NamingStrategy in the constructor (assuming you are using Json.Net 9.0.1 or later). You can add this same code to the constructor of yourNullToEmptyStringResolver.

public class NullToEmptyStringResolver : DefaultContractResolver
{
    public NullToEmptyStringResolver() : base()
    {
        NamingStrategy = new CamelCaseNamingStrategy
        {
            ProcessDictionaryKeys = true,
            OverrideSpecifiedNames = true
        };
    }

    ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...