Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No Json.net constructor with settings and converter parameters

Tags:

json.net

We are currently using the following constructor.

var text = JsonConvert.SerializeObject(message, new IsoDateTimeConverter());

the problem we are facing is that the json is sometimes serialized in a different order. This causes an issue with our tests and the hash check we do. I found an example that can order the properties using customer settings

public class OrderedContractResolver : DefaultContractResolver
{
    protected override System.Collections.Generic.IList<JsonProperty> CreateProperties(System.Type type, MemberSerialization memberSerialization)
    {
        return base.CreateProperties(type, memberSerialization).OrderBy(p => p.PropertyName).ToList();
    }
}

you would normally use this by initializing a JsonSerializationSettings object and pass it into the constructor like

var settings = new JsonSerializerSettings()
{
    ContractResolver = new OrderedContractResolver()
};

var json = JsonConvert.SerializeObject(obj, Formatting.Indented, settings);

the problem with this is i can't see an overload for the constructor that uses a converter and a settings parameter, any ideas how i can use both?

like image 552
Ryan Burnham Avatar asked Oct 15 '12 01:10

Ryan Burnham


1 Answers

Found it, there is a converters property on the settings object.

var settings = new JsonSerializerSettings()
{
     ContractResolver = new OrderedContractResolver()
};
settings.Converters.Add(new IsoDateTimeConverter());

var text = JsonConvert.SerializeObject(message, Formatting.Indented, settings);
like image 80
Ryan Burnham Avatar answered Jan 03 '23 21:01

Ryan Burnham