java - Object.parse 中的 JSON 意外标记

标签 java javascript json angularjs spring-security

我正在使用 Spring Security 并尝试显示登录用户的 Angular 色。

Spring Sec 正在运行 - 我有工作注册和登录 JS 功能(我可以在数据库中看到新用户,并且我可以进行有效登录),但是当我尝试获取当前用户的 Angular 色信息并通过前端简单 html 文件中的简单 {{role}} 显示它时,我收到此错误:

enter image description here

但我仍然收到来自 JSON 的有效响应:

enter image description here

enter image description here

这是我的 user.html,其中 data-ng-init 和 {{role}} 是:

<div class="masthead">
    <h4 class="text-center" data-ng-init="init()">
        <strong>Users Home Screen</strong>
    </h4>
    <p>{{role}}</p>
    <br>
...
</div>

这是我的 userController.js (它通过 app.js 连接到 user.html):

collectionsApp.controller('userController', function($scope, userService,
        $state) {
    $scope.init = function() {
        userService.getAuthorization(displayRole);
    }

    displayRole = function(response) {
        $scope.role = response.data;
    }

});

我的userService.js:

collectionsApp.service('userService', function($http) {
    return {
        login : function(user, callback) {
            $http.post('/user/login', user).then(callback);
        },
        register : function(user, callback) {
            $http.post('/user/add', user).then(callback);
        },

        getAuthorization : function(callback) {
            $http.get('/user/getAuthorization').then(callback);
        }

    };
}); 

我的 UserController.java(本文中仅显示感兴趣的函数):

@RequestMapping(value = "/getAuthorization", method = RequestMethod.GET)
public String getAuthorization() {
return SecurityContextHolder.getContext().getAuthentication().getAuthorities().toString();
}

哦,还有一件奇怪的事情: 当我设置断点(如下图所示)并在 user.html 上按 f5 时,调试就像永远不会到达断点一样,并在控制台中报告提到的 SyntaxError。如果你问我的话,那是相当超自然的……:)

enter image description here

最佳答案

您的响应不是有效的 JSON。如果将包含单个字符串元素“SOME_ROLE”的数组转换为 JSON,则会生成 ["SOME_ROLE"]。如果您使用 Google 的 Gson 库,您可以执行以下操作:

Gson gson = new Gson();
gson.toJson(new String[]{SecurityContextHolder.getContext().getAuthentication().getAuthorities().toString‌​()});

关于java - Object.parse 中的 JSON 意外标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25407527/

相关文章:

javascript - 使用来自 GET 请求的 JSON 数组填充数据表

java - getLastKnownLocation 与请求位置更新

java - 这是函数、变量还是其他东西

javascript - 当asp :linkbutton is clicked时如何用data-id填充隐藏字段

javascript - 同时更改所有文本区域的大小

javascript - Angular js - json 上的简单循环不起作用

java - 无法通过使用 Amazon Corretto 8 双击它来运行可执行 jar 文件

java - 尝试从 URI 获取文件名时出现致命的运行时异常

javascript - 你如何实现 fetch api?

javascript - 如何去掉 JSON 字符串的外部参数?