Convert properties with specific attribute to JSON string

Viewed 92

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();
        }
    }
1 Answers

Small refactoring to make use of new JsonSerializer from System.Text.Json namespace:

public string FormatKeyAttributesAsJson2<T>(object value)
{
    lock (lockObject)
    {
        BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
        // create here a Dictionary<string, object>
        var dict = typeof(T).GetProperties(flags)
            .Where(p => p.GetCustomAttribute<KeyAttribute>() != null)
            .ToDictionary<PropertyInfo, string, object>(p => p.Name, p => p.GetValue(value));
        // which will be seriazlied without any problems
        return JsonSerializer.Serialize(dict);
    }
}
Related