【问题标题】:AngularJS is not parsing our JSON array propertyAngularJS 没有解析我们的 JSON 数组属性
【发布时间】:2023-04-07 20:10:01
【问题描述】:

我们的 GET 请求返回以下响应:

{
    "access_token": "pi7ID4bsZIC9yN ... 76gnblw",
    "token_type": "bearer",
    "expires_in": 1209599,
    "userName": "super0",
    "userRoles": "["member", "admin"]",
    ".issued": "Tue, 04 Feb 2014 05:07:51 GMT",
    ".expires": "Tue, 18 Feb 2014 05:07:51 GMT"
}

问题在于 AngularJS 将其解析为以下对象。

data: Object
    .expires: "Tue, 18 Feb 2014 05:07:51 GMT"
    .issued: "Tue, 04 Feb 2014 05:07:51 GMT"
    access_token: "pi7ID4bsZIC9yN ... 76gnblw"
    expires_in: 1209599
    token_type: "bearer"
    userName: "super0"
    userRoles: "["member", "admin"]"
    __proto__: Object

我们需要“userRoles”来解析成一个 JavaScript 数组而不是一个字符串,如图所示。我们该怎么做?

【问题讨论】:

    标签: javascript arrays json angularjs parsing


    【解决方案1】:

    这不是有效的 JSON。该数组不应被引用。

    它应该看起来像这样:

    {
        "access_token": "pi7ID4bsZIC9yN ... 76gnblw",
        "token_type": "bearer",
        "expires_in": 1209599,
        "userName": "super0",
        "userRoles": ["member", "admin"],
        ".issued": "Tue, 04 Feb 2014 05:07:51 GMT",
        ".expires": "Tue, 18 Feb 2014 05:07:51 GMT"
    }
    

    【讨论】:

    • 啊哈。这就说得通了。那么问题是我无法返回一个不带引号的数组,因为 C# 从 Dictionary 创建 JSON GET 响应。 JSON属性值必须是字符串,不知道引号外怎么加方括号data.Add("userRoles", "['admin', 'member']");
    • 你能把它改成Dictionary<string, object>,所以userRoles键的值可以是一个数组(或某种类型的IEnumerable)吗?然后,它应该正确序列化。
    • 我可以尝试,但我很犹豫。 ASP.NET Identity 的 AuthenticationProperties() 构造函数采用 Dictionary。实现我们自己的 AuthenticationProperties 类可能会成功。不过,这将需要一些工作。嗯。
    • 我可能只是将 userRoles 作为 CSV 传递。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    • 1970-01-01
    • 2018-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多