I have an alternate JsonResult, being the class below, to provide a better JSON serializer than the default for MVC Web Apps (irrelevant bits omitted):

public class JsonDotNetResult : JsonResult
    public readonly JsonSerializerSettings Settings = new JsonSerializerSettings
        PreserveReferencesHandling = PreserveReferencesHandling.Arrays,
        ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
        ContractResolver = new CamelCasePropertyNamesContractResolver(),
        Converters = new List<JsonConverter> { new StringEnumConverter() }

    public override void ExecuteResult(ControllerContext context)
        var response = context.HttpContext.Response;
        response.Write(JsonConvert.SerializeObject(Data, Settings));

Then I have an overload for Controller.Json, declared as:

protected JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior, JsonSerializerSettings settings = null)

but I don't have the existing default settings set in the Settings field of JsonDotNetResult, so if I pass in a new JsonSerializerSettings, with a few properties set by the caller, I will overwrite all the properties of the Settings object with the default values for JsonSerializerSettings, and with the new values provided by the caller. The latter being desired, the former I'm trying to avoid.

How can I pass in a subset of JsonSerializerSettings property values and apply them to the Settings object in JsonDotNetResult? My best (and first) effort is to loop through the properties of the default Settings object and compare them to property values on a new JsonSerializerSettings object passed by the user, and where the differ, set the value on Settings to the value supplied by the user.

Related posts

Recent Viewed