0

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?

14
  • 8
    Have you tried anything yet? This looks like JSON but implemented badly. Can you affect this string? Commented Apr 30, 2018 at 15:26
  • 1
    It's not valid JSON (unquoted strings) but maybe you could use the AlmostJson.NET library. /s I suggest fixing the input so you can simply use a JSON deserializer like Json.NET. Commented Apr 30, 2018 at 15:27
  • 1
    @user2366842 yes but I would push like hell to get it fixed. Writing a custom JSON parser is a non-trivial task, and likely a never-ending stream of edge cases due to invalid input. Commented Apr 30, 2018 at 15:34
  • 3
    @test The point is that it's not valid JSON so you can't use JObject or JsonConvert, unless you fix the source data - is that possible? Commented Apr 30, 2018 at 15:35
  • 2
    Nope i can't change it, the source will always be a string like in the example Commented Apr 30, 2018 at 15:37

2 Answers 2

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

using Newtonsoft.Json;

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.