1

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 Answer 1

4

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.