Object.parse上的JSON意外标记

时间:2014-08-20 14:36:06

标签: java javascript json angularjs spring-security

我正在使用Spring Security并尝试显示已插入的用户的角色。

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

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

1 个答案:

答案 0 :(得分:1)

您的回复无效JSON。如果将包含单个String元素&#34; SOME_ROLE&#34;的数组转换为JSON,则会生成["SOME_ROLE"]。如果您使用的是Google的Gson库,则可以执行以下操作:

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