Alamofire参数json格式的bug

时间:2016-01-12 12:21:41

标签: ios swift alamofire

我有这个辅助函数来创建json作为参数和我的PUT请求一起传递。

static func helperProfileParametersWith(user: User?, username: String?, email: String?, meta_motto: String?, meta_status: String?) -> [String: AnyObject] {
    if let user = user {
        return ["username": username ?? "", "email": email ?? "", "status": user.status ?? "", "meta": ["status": meta_status ?? "", "motto": meta_motto ?? ""], "type":user.type ?? ""]
    }
    return [String:AnyObject]()
}

输出将

{
  username: "admin", 
  email: "xx@xx.xx", 
  status: "banned",
  meta: {
    status: "I am happy today",
    motto: "i love coding"
  }
}

然后我将参数传递给函数

static func updateUserProfile(userId: String, parameters: [String: AnyObject], failure: ((NSError)->Void)?, success: ([String: AnyObject], Set<String>)->Void) {

    Alamofire.request(.PUT, API.baseUrl + API.user.fetchUpdateProfile + "/" + userId, parameters: parameters).responseJSON {
        response in
    }
}

但是从我的NodeJS服务器,我得到的是

{
  username: "admin", 
  email: "xx@xx.xx", 
  status: "banned",
  meta["status"]: "I am happy today",
  meta["motto"]: "i love coding"
}

正如您所看到的那样,子词典被&#34;展平&#34;,键变为meta["motto"]字符串,而不是meta,然后是motto

我很确定我的服务器不是问题,因为我的Angular客户端工作正常。

注意:如果你很好奇。我使用ng-resource以正确的格式发送JSON。

app.factory('Profile', ['$resource', function($resource) {
    return $resource(constant.webapi.user.fetchUpdateProfile, {profileId: '@_id'}, {
        update: {method: 'PUT'}
    })
}])



$scope.updateProfile = function() {
    $scope.profile.$update(function(data) {
        data = helper.dataAppendedWithMessage(data, 'success', 'success update profile')
        $scope.profile = data
        helper.showMessage($scope, data, false)
    },
        //helper.callbackToShowMessage($scope, false)
        function(err) {
            //Note: if fail to update, reload the page.
            //Otherwise we have to revert back to original, which is tedious to do
            helper.showMessage($scope, err.data, true) //since we reload the page, store message in $cookies
            $window.location.reload(true)
        })
}

1 个答案:

答案 0 :(得分:0)

确保您发送Content-Type“application / json”以及Alamofire请求。