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
JsonIgnoreattribute.If I create a
Termsobject like this:And if
SecretTermlooks 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
ReadJsonunimplemented - I don't think it's necessary as you can easily deserialize aTermsobject without using a converter. In this case theSecretTermproperty would simply be empty.By using the converter you won't need the
[JsonIgnore]attribute on theSecretTermproperty.