iOS Game Center在匹配数据中发送json

时间:2014-04-11 22:14:57

标签: ios game-center

我试图在用户结束时在matchData对象中发送JSON数据。如果我在发送之前检查json是有效的,看起来像,

JSON:

{
  "p1score" : "0",
  "turn" : "0",
  "pb1" : "BPS1120|2231|3422|4213|5244|6135",
  "player2" : "0000177110",
  "player1" : "0000177110",
  "p2score" : "0",
  "movements" : "MVS2242",
  "pb2" : "BPS1630|2511|3522|4543|5534|6625",
  "moves" : "30"
}

准备要发送的数据

NSData *matchData = [[NSString stringWithFormat:@"%@",realMatchData] dataUsingEncoding:NSUTF8StringEncoding];

realMatchData包含上面的json字符串。

但是如果再次将matchData转换回字符串以检查使用的是什么,

NSString *str = [[NSString alloc] initWithData:matchData encoding:NSUTF8StringEncoding];

我找回了以下json字符串

{
  "moves" : "30",
  "turn" : "0",
  "player2" : "G:0000177110",
  "p1score" : "0",
  "player1" : "G:0000177110",
  "movements" : "MVS",
  "p2score" : "0"
}

密钥pb1pb2缺失。

我的事件试图将pb1pb2的值作为嵌套json传递,但问题仍然相同,发送数据时它们的密钥丢失。

是分享游戏状态的正确方法还是我应该使用其他方法来共享数据?

感谢。

1 个答案:

答案 0 :(得分:0)

这不能完全回答这个问题,但它可以解决问题,并且提问者要求举例。 Apple提供了自己的JSON序列化,它从JSON可序列化对象(如NSNumber, NSArray, NSString, NSDictionary,等)生成NSData对象。

NSMutableArray* matchArray = [NSMutableArray array];

/*
   Fill the match array with the appropriate objects to represent your game state...
   You've presumably already done this in order to get that string object...
*/

NSData* matchData =  [NSJSONSerialization dataWithJSONObject: matchArray 
                               options: 0 //pretty sure all the options here are irrelevant for our purposes
                                 error: NULL]; //pass in a pointer to an NSError if you are interested in the error

//end the turn or do whatever one does in a non-turn-based match with matchData as the data object