简体   繁体   中英

Deserialize JSON to C# object to display nested array as string in grid

Everything run and Deserialize OK. Except the Roles is show up as System.Collections.Generic.List`1[System.String]

Problem

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": "test@test.com",
    "Roles": ["Admin","User","Guest"],
    "Age":"23"
},
{
  "Name":"test1",
  "Email": "test1@test.com",
  "Roles": ["Admin", "User" ,"Guest"],
  "Age":"33"
}]

Model

public class example
{
    public string Name { get; set; }
    public string Email { get; set; }
    public IList<string> Roles { get; set; }
    public string Age { get; set; }
}

Deserialization

List<Exampe> list = JsonConvert.DeserializeObject<List<Exampe>>(bundle);

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>()); } 
  • Or by altering the DataSource of the DataGridView :

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

You have Name twice in your class - you probably want:

public class example
{
    public string Name { get; set; }
    public string Email { get; set; }
    public IList<string> Roles { get; set; }
    public string Age { get; set; }
}

If I understand correctly you seem to want to get string[] instead of List<string>

Roles can be string[]

public class Example
{
    public string Name { get; set; }
    public string Email { get; set; }
    public string[] Roles { get; set; }
    public string Age { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM