I wrote the following function below to convert an object with properties that have a [Key] attribute to a JSON string. It seems like a lot of code to me, is there a more modern feature I can take advantage of to refactor this?
public string FormatKeyAttributesAsJson<T>(object value)
{
lock (lockObject)
{
BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
var properties = typeof(T).GetProperties(flags)
.Where(p => p.GetCustomAttribute<KeyAttribute>() != null)
.ToList();
StringBuilder jsonString = new StringBuilder();
jsonString.Append("{");
for (int i = 0; i < properties.Count; i++)
{
if(i == properties.Count - 1)
{
jsonString.Append($"\"{properties[i].Name}\":\"{properties[i].GetValue(value)}\"");
}
else
{
jsonString.Append($"\"{properties[i].Name}\":\"{properties[i].GetValue(value)}\",");
}
}
jsonString.Append("}");
return jsonString.ToString();
}
}