Hapi - 如何将有效负载解析为JSON?

时间:2014-10-06 02:37:51

标签: json swift

所以我试图一次性研究HTTP / TCP / IP协议,Nodejs,MongoJS和MongoDB。所以我试图用Hapi Web Framework找出一些东西。我能够通过我的iOS模拟器与服务器通信,但我似乎无法正确解析有效负载。我知道我可以使用URL中的参数来发送信息,但我想使用有效负载。

所以我最终把它保存到Mongo中。

(
    {
    "_id" = 5431f161bb859872034d2456;
    "{\"userLastNameKey\":\"Kwon\",\"userEmailKey\":\"email\",\"userFirstNameKey\":\"Michael\",\"userUsernameKey\":\"username\",\"userPasswordKey\":\"password\"}" = "";
},
    {
    "_id" = 5431fe5694ed4721046c1f8c;
    "{\"userLastNameKey\":\"Kwon2\",\"userEmailKey\":\"email2\",\"userFirstNameKey\":\"Michael2\",\"userUsernameKey\":\"username2\",\"userPasswordKey\":\"password2\"}" = "";

这是我的呼叫的hapi代码。

    // This will add a new user to the database
function addUser(request, response){

    db.usersCollection.save(request.payload, function (err, saved){
        if(err || !saved)
        {
            console.log("User not saved");
        } else 
          {
              console.log("User saved");
          }
    });
}

我的最终结果我想尝试让它像这样

    (
    {
    "_id" = 5431f161bb859872034d2456,
    "userLastNameKey" = "Kwon", 
    "userEmailKey" = "email",
    "userFirstNameKey"= "Michael",
    "userUsernameKey" = "username",
    "userPasswordKey" = "password",
    }
)

这是iOS代码

   NSDictionary *userData = [User userToDictionary: newUserInfo];
   NSData *userJSON = [NSJSONSerialization dataWithJSONObject: userData options: 0 error: nil]; 

 NSURL *url = [NSURL URLWithString: urlString];
 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url];
 [request setHTTPMethod: @"POST"];
 [request addValue: @"application/json" forHTTPHeaderField: @"Content-Type"];

    // This will set up the url session
    NSURLSessionConfiguration* config = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration: config];

    NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest: request fromData: userJSON completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

            if(error)
            {

            } else
              {

              }

          }];

          [uploadTask resume];
      }

任何人都知道如何实现这一目标?

1 个答案:

答案 0 :(得分:1)

{
  "_id" = 5431f161bb859872034d2456;
  "userLastNameKey" = "Kwon"; 
  "userEmailKey" = "email";
  "userFirstNameKey"= "Michael";
  "userUsernameKey" = "username";
  "userPasswordKey" = "password";
}

那是不是JSON对象。您需要使用逗号而不是分号。和冒号而不是平等。您的ID也不是十进制数字,因此最好将其设为字符串。

您的对象看起来像:

{
  "_id" : "5431f161bb859872034d2456",
  "userLastNameKey" : "Kwon",
  "userEmailKey" : "email",
  "userFirstNameKey" : "Michael",
  "userUsernameKey" : "username",
  "userPasswordKey" : "password"
}

要解析(格式正确的)JSON字符串,请使用:var JSONObject = JSON.parse(JSONstring);