问题描述
一切正常,然后反序列化确定.除了角色以外,其他信息都显示为System.Collections.Generic.List`1 [System.String]
Everything run and Deserialize OK. Except the Roles is show up as System.Collections.Generic.List`1[System.String]
问题
如果我想将每个字段附加到网格.有没有办法在不循环Roles属性的情况下将集合显示为字符串?
If I want to attach each field to a grid. Is there a way to show the collection as a string without looping through the Roles property?
JSON
[{
"Name":"test",
"Email": "[email protected]",
"Roles": ["Admin","User","Guest"],
"Age":"23"
},
{
"Name":"test1",
"Email": "[email protected]",
"Roles": ["Admin", "User" ,"Guest"],
"Age":"33"
}]
型号
public class example
{
public string Name { get; set; }
public string Email { get; set; }
public IList<string> Roles { get; set; }
public string Age { get; set; }
}
反序列化
List<Exampe> list = JsonConvert.DeserializeObject<List<Exampe>>(bundle);
推荐答案
如@Nkosi所述,这是一个XY问题.问题不在于反序列化,而是 DataGridView
如何处理复杂"属性类型.
As @Nkosi mentioned, this is a XY problem. The problem is not deserialization, but rather how DataGridView
handles a "complex" property type.
您可以添加一个新属性以显示它:
You can add a new property to display it:
-
直接修改类定义即可:
Either by directly modifying the class definition:
public class Example
{
public string Name { get; set; }
public string Email { get; set; }
public string[] Roles { get; set; }
public string Age { get; set; }
public string RolesText => string.Join(", ", Roles ?? Array.Empty<string>());
}
或通过更改 DataGridView
的 DataSource
:
dgv.DataSource = list.Select(x => new
{
x.Name, x.Email, x.Age,
Roles = string.Join(", ", x.Roles ?? Array.Empty<string>()),
}).ToList();
-
奖金:这是第二种方法的产生器:
Bonus: Here is an generator for the 2nd approach:
string GenerateModelFormatter<T>()
{
return new StringBuilder()
.AppendLine("x => new")
.AppendLine("{")
.AppendLine(string.Join(",\n", typeof(T).GetProperties()
.Select(x => x.PropertyType != typeof(string[])
? $"\t{x.Name} = x.{x.Name}"
: $"\t{x.Name} = string.Join(\", \", x.{x.Name} ?? Array.Empty<string>())")))
.AppendLine("}")
.ToString();
}
这篇关于将JSON反序列化为C#对象以将嵌套数组显示为网格中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!