Patrick
Patrick

Reputation: 383

Serialize c# array of strings to JSON array

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 '[& quot;user& quot;,& quot;'admin& quot;]' 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;        
    }
}

Upvotes: 7

Views: 26505

Answers (2)

kingPuppy
kingPuppy

Reputation: 3047

It'd be nice if razor makes a native method for this.

In the meantime here is a simple (Without libraries) for-loop to accomplish it:

 @{
    <script>var array = []; </script> //create an empty js array

      for(int i = 0; i < Model.Count; i++)
      {
        <script> array[@i] = '@Model[i]'; </script> //pass each string to array
      }
 }

Upvotes: 0

user240141
user240141

Reputation:

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

Upvotes: 13

Related Questions