将具有特定属性的属性转换为 JSON 字符串
Convert properties with specific attribute to JSON string
我在下面编写了以下函数,将具有 [Key]
属性的对象转换为 JSON 字符串。对我来说似乎有很多代码,有没有更现代的功能我可以利用它来重构它?
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();
}
}
小重构以使用 System.Text.Json 命名空间中的新 JsonSerializer:
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);
}
}
我在下面编写了以下函数,将具有 [Key]
属性的对象转换为 JSON 字符串。对我来说似乎有很多代码,有没有更现代的功能我可以利用它来重构它?
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();
}
}
小重构以使用 System.Text.Json 命名空间中的新 JsonSerializer:
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);
}
}