字典到JSON的编码数组中的问题

时间:2018-10-12 10:36:21

标签: json swift nsarray nsdictionary

在POST请求中,我必须发送以下JSON数据

def welcome_email(user)
  @user = params[:user]
  @url  = 'http://example.com/login'
  recipients    "test123@gmail.com"
  from          "example@gmail.com"
  subject       "Test"
  sent_on       Time.now
  body          {:user => @user, :url => @url}
end

我正在尝试

{
    "users": [{"userid": 16, "meetAt":"Some place (College/trip etc)", "showFields": "11111111000"}, {"userid": 17, "meetAt":"Some place (College/trip etc)", "showFields": "11111111001"}]
}

我在调试器中看到static func linkRequestBody(userDetails: ScannedContact) -> Any { let jsonToRegistrer = [["userid":userDetails.id, "meetAt":"Defalut Test Location at", "showFields":userDetails.showFields]]; return jsonToRegistrer; } userDetails.id具有有效值,但仍然失败。

错误:

userDetails.showFields

2 个答案:

答案 0 :(得分:4)

这是您的目标格式:

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class Uppercase implements Rule
{
    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        return $value == 'required|string|max:100';//something like this
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The :attribute must be uppercase.';
    }
}

在调用{ "users": [{ "userid": 16, "meetAt": "Some place (College/trip etc)", "showFields": "11111111000" }, { "userid": 17, "meetAt": "Some place (College/trip etc)", "showFields": "11111111001" }] } 之后(或者如果您的代码接受Dictionary / Array并自己进行翻译):

JSONSerialization

应该表示:

let jsonToRegistrer =  [["userid":userDetails.id, "meetAt":"Defalut Test Location at", "showFields":userDetails.showFields]];

您看到问题了吗?您的版本是[{ "userid": 16, "meetAt": "Defalut Test Location at", "showFields": "11111111000" }] ,而目标版本是Array,因此您错过了Dictionary键。

要修复它:

users

为了清楚起见,您也不能将其写成一行:

let jsonToRegistrer =  ["user": [["userid":userDetails.id, "meetAt":"Defalut Test Location at", "showFields":userDetails.showFields]]];

因此,问题在于您的版本没有采用所需的相同格式。

要查看以JSON呈现的版本,您可以使用:

let jsonToRegistrer = ["user": [
                                 ["userid": userDetails.id,
                                  "meetAt": "Defalut Test Location at",
                                  "showFields": userDetails.showFields]
                                ]
                        ];

答案 1 :(得分:1)

我个人会通过使用struct thant实现Codable来避免此问题。由于您没有任何类型的值,也没有递归字段,因此应该很容易

struct Users: Codable {
    var users: [User]
}

struct User: Codable {
    let userid: Int
    let meetAt: String
    let showFields: String
}

然后,您只需要在User中绑定Users.users就可以轻松对其进行编码

do {
    let json = try? JSONEncoder().encode(Users)
} catch { // whatever you want }

This article可能有助于您更好地了解可编码协议。 希望对您有帮助!