I have a Person
class with custom attribute over few properties, I want to serialize this class object using Newtonsoft JSON.NET features. My custom attribute should also get serialized into the JSON.
Do we have anything built-in in Newtonsoft JSON.NET for this?
public class Person
{
public Int32 Id { get; set; }
public String FirstName { get; set; }
public String LastName { get; set; }
[Encrypted(key="PersonalData")]
public String Address { get; set; }
[Encrypted(key="PersonalData")]
public String Phone { get; set; }
[Encrypted(key="PersonalData")]
public String IdentityDetails{ get; set; }
}
When the JSON string gets exported through serialization, the applied custom attributes over the properties should also get exported as part of the JSON, so that by looking at the JSON data, we can identify that those property value are encrypted. So that other program where we are sending the JSON string can take the action accordingly for those property value, my class is not fixed, we can send any class JSON string to other program that is responsible to read the JSON and process that.
11
No, Newtonsoft JSON.NET doesn’t natively serialize custom attributes, but you can achieve this by creating a custom JsonConverter.
But you can try this approach:
- Custom Attribute:
[AttributeUsage(AttributeTargets.Property)]
public class EncryptedAttribute : Attribute
{
public string Key { get; }
public EncryptedAttribute(string key) => Key = key;
}
- Custom JsonConverter:
public class YourCustomAttributeJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType) => objectType.IsClass;
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteStartObject();
foreach (var prop in value.GetType().GetProperties())
{
writer.WritePropertyName(prop.Name);
serializer.Serialize(writer, prop.GetValue(value));
var encryptedAttr = prop.GetCustomAttribute<EncryptedAttribute>();
if (encryptedAttr != null)
{
writer.WritePropertyName($"{prop.Name}_Encrypted");
writer.WriteStartObject();
writer.WritePropertyName("Key");
writer.WriteValue(encryptedAttr.Key);
writer.WriteEndObject();
}
}
writer.WriteEndObject();
}
// Not needed for serialization-only
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
=> throw new NotImplementedException();
}
Program.cs:
var person = new Person { /* set properties */ };
var settings = new JsonSerializerSettings();
settings.Converters.Add(new CustomAttributeJsonConverter());
var json = JsonConvert.SerializeObject(person, settings);
Console.WriteLine(json);
This will include the Encrypted attribute metadata in your JSON output.
But I agree with other commentators, think twice whether this is the only way to reach your goal 😉
Manolii Horditsa is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1