Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

i have the following code in my _Layout.cshtml file. The idea is that in my javascript code some items about the security are filled in. LoggedIn and username are obviously no problem, but the way the roles are put in the javascript is wrong. The Roles is simply a string[] (that should become a JSON array.

But it shows as a '["user","'admin"]' which obviously is not a valid JSON array. Any ideas how i can convert my string array to a valid JSON array? My code of the RolesArray is added below.

<script type="text/javascript">
    $(function () {
        require(['jquery','config', 'security'],
                function ($, config, security) {

                security.items.loggedIn = '@Request.IsAuthenticated';
                security.items.Username = '@User.Identity.Name';

                var one = '@((MyIdentity)User.Identity).RolesArray'
                $(document).trigger("security_changed");
           });
    });
</script>


public String[] RolesArray   
{
    get
    {
        var two = Roles.ToArray();
        return two;        
    }
}
share|improve this question

1 Answer

Use JSON.Net See the code below

Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };

string json = JsonConvert.SerializeObject(product);
//{
//  "Name": "Apple",
//  "Expiry": "2008-12-28T00:00:00",
//  "Price": 3.99,
//  "Sizes": [
//    "Small",
//    "Medium",
//    "Large"
//  ]
//}

Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.