test
test

Reputation: 127

Convert a string to an array of objects

How can I convert a string to an array of objects?

I am working with the following string

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

and i want to be able to convert it to a .net object such as

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

Is this possible?

Upvotes: 0

Views: 314

Answers (2)

mohammad mohammad
mohammad mohammad

Reputation: 394

you could use Newtonsoft.Json, since your string is a JSON compaible one:

using Newtonsoft.Json;

var myObject = JsonConvert.DeserializeObject<List<StaffAccountObj>>(s);

Upvotes: 0

DavidG
DavidG

Reputation: 118937

One solution is to use a regular expression to find the matches. Now this is a bit fragile, but if you are sure your input is in this format then this will work:

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

And loop through them like this:

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

Upvotes: 2

Related Questions