during run time I'd like to print JSon to log but censor one of its fields. I use JSon.Net and have all the attributes, for example
public Class Terms
{
[JsonProperty("Term")]
string term
[JsonProperty("SecretTerm")]
string SecretTerm
public string toCensoredString()
{
// I need to get a JSON string with only the regular term and not the secret
var jsonRequest = JsonConvert.SerializeObject(this);
// .....
}
}
What will be the best way to eliminate specific field in runtime in my new ToCensoredString() function?
By far the easiest approach is to use the
JsonIgnore
attribute.If I create a
Terms
object like this:And if
SecretTerm
looks like this:Your serialized Json will look like this:
If you want more fine-grained control you will have to create a custom converter.
Edit:
To more selectively output the object, you need the custom converter:
When serializing, you would do this:
You'll note that I have left the
ReadJson
unimplemented - I don't think it's necessary as you can easily deserialize aTerms
object without using a converter. In this case theSecretTerm
property would simply be empty.By using the converter you won't need the
[JsonIgnore]
attribute on theSecretTerm
property.