将字符串的C#数组序列化为JSON数组 [英] Serialize c# array of strings to JSON array

查看:141
本文介绍了将字符串的C#数组序列化为JSON数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的_Layout.cshtml文件中包含以下代码.这个想法是在我的javascript代码中填写了一些有关安全性的项目.LoggedIn和用户名显然没有问题,但是角色在javascript中的放置方式是错误的.角色只是一个字符串[](应成为JSON数组.

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.

但显示为'[&使用者和使用者",& quot'admin& "]",这显然不是有效的JSON数组.有什么想法可以将我的字符串数组转换为有效的JSON数组吗?我的RolesArray代码在下面添加.

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

推荐答案

使用JSON.Net 参见下面的代码

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

这篇关于将字符串的C#数组序列化为JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆