Refactor of ShouldSerialize () in class… can I use IContractResolver?

前端 未结 1 794
误落风尘
误落风尘 2021-01-24 00:42

I have an API that returns a big list of car features.... all are either bool or ints... and basically I only want to display the ones that return true values or >0 for the ints

相关标签:
1条回答
  • 2021-01-24 01:43

    It sounds like what you are trying to accomplish by writing all these ShouldSerialize() methods can be accomplished by just changing the DefaultValueHandling setting on the serializer to Ignore. This will cause any values that are equal to their default values (false for bool, 0 for int) not to be serialized.

    JsonSerializerSettings jsonSettings = new JsonSerializerSettings();
    jsonSettings.DefaultValueHandling = DefaultValueHandling.Ignore;
    
    string json = JsonConvert.SerializeObject(yourObject, jsonSettings);
    

    If you're using Web API, then you can access the settings of the Json.NET serializer via the Register method of the WebApiConfig class (in the App_Start folder).

    JsonSerializerSettings settings = config.Formatters.JsonFormatter.SerializerSettings;
    settings.DefaultValueHandling = DefaultValueHandling.Ignore;
    
    0 讨论(0)
提交回复
热议问题