Newtonsoft.Json
Newtonsoft.Json copied to clipboard
Feature Request: Allow attributes to be applied to only serializing or deserializing
It would be great if we could tell attributes like [JsonProperty] and [JsonIgnore] to apply only to serialization or deserialization rather than always applying to both. I know I can pass a Json settings object to customize behavior for a specific call to JsonConvert or write custom code but it can be cumbersome and does not always provide quite the right behavior.
Example C# Class
public class ServiceCode
{
public string field_name { get; set; }
public string region { get; set; }
public string code_id { get; set; }
}
and I want the code_id field to get populated during deserialization but not when serializing. I might want this property available for me to refer to in C# code but when producing the final JSON output for the API I'm writing, the user consuming the data shouldn't see it. Currently I can write custom code to achieve this, as I saw in the Newtonsoft documentation, but it just seems like a far cleaner solution would be something like:
...
[JsonIgnoreOnSerialize]
public string code_id { get; set; }
...
Or maybe as a parameter, like this:
[JsonIgnore OnlyOnSerialize=True]
If something like this already exists (other than having to write the custom code I mentioned earlier) please let me know.
This feature was also something I was hoping existed today, and searching issues I found this earlier issue here that also asks for this feature: https://github.com/JamesNK/Newtonsoft.Json/issues/1970
The reason this feature is important is that some attributes are input only. For example, sending a secret from the client to server but you never want to return that secret to the client. There are ways to work around this but the bottom line is you want a simple way to ensure the team can get it right the first time. More complex solutions have a high risk of breaking or being bypassed increasing the risk that secrets are disclosed to the client.
Do we have any upcoming plan for this feature?