将字符串转换为对象数组

时间:2018-04-30 15:25:54

标签: c# asp.net .net arrays string

如何将字符串转换为对象数组?

我正在使用以下字符串

public class StaffAccountObj
{
    public string role { get; set; }
    public string storeId { get; set; }
}

我希望能够将其转换为.net对象,例如

{{1}}

这可能吗?

2 个答案:

答案 0 :(得分:2)

一种解决方案是使用正则表达式来查找匹配项。现在这有点脆弱,但如果您确定您的输入采用这种格式,那么这将起作用:

var s = "[{role:staff, storeId: 1234}, {role:admin, storeId: 4321}]";

//There is likely a far better RegEx than this...
var staffAccounts = Regex
    .Matches(s, @"\{role\:(\w*), storeId\: (\d*)}")
    .Cast<Match>()
    .Select(m => new StaffAccountObj
    {
        role = m.Groups[1].Value,
        storeId = m.Groups[2].Value
    });

像这样循环遍历:

foreach (var staffAccount in staffAccounts)
{
    var role = staffAccount.role;
}

答案 1 :(得分:0)

您可以使用Newtonsoft.Json,因为您的字符串是可以使用JSON的字符串:

using Newtonsoft.Json;

var myObject = JsonConvert.DeserializeObject<List<StaffAccountObj>>(s);
相关问题