Node.JS
Node.JS

Reputation: 1570

Trying to extend SerializeObject method of Newtonsoft.Json.JsonConvert

I am try to extend Newtonsoft.Json.JsonConvert to make returned JSON always formatted but I am getting an error "cannot declare variable of static type Newtonsoft.Json.JsonConvert". I don't know what is wrong with the code, is it because I cannot extend static class JsonConvert? maybe my approach is fundamentally wrong because extension method would not override instance method. I am not sure.

using Newtonsoft.Json;

namespace SomeNameSpace
{
    public static class MakeSerializationPrettyAlways
    {
        public static string SerializeObject(this JsonConvert jc, object value)
        {
            return JsonConvert.SerializeObject(value, Formatting.Indented);
        }
    }
}

Upvotes: 0

Views: 1061

Answers (1)

Eric
Eric

Reputation: 1847

JsonConvert is a static class. You can't create an extension method using a static class as the target.

The following should change your default serialization:

JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
    Formatting = Formatting.Indented
};

Upvotes: 2

Related Questions