2012-03-12 91 views
1

我需要制作如下所示的json参数。iPhone:为服务器请求格式化json时出现问题

最终输出应该是,

{"submissionTime":"\/Date(1331549630849)\/", 
"statusId":"0", 
"answers":[{"answer":"Yes","qid":167},{"answer":"Hello","qid":168}], 

"participantId":"16369", 
"token":"t_ikHOXVjlcsSb9Tfdn5RaO54JGQobHodUD5881SKevxy63jwLxe8ZPQvXYss4pR"} 

我试图让这种格式。我得到了时间,状态,参与和令牌。没关系。但是,我在制作“answers”数组时遇到了问题。

我使用下面的代码来制作如下所示的答案json格式。

NSArray *answerkeys = [NSArray arrayWithObjects:@"answer", @"qid",nil]; 
      NSString *qID = [NSString stringWithFormat:@"%d", [questionidArray objectAtIndex:i] ]; // for loop 
      NSArray *objectkeys = [NSArray arrayWithObjects:value, qID,nil];    
      NSString *answerjsonRequest = [pSr makeJSONObject:objectkeys :answerkeys]; 
answerjsonRequest = [(NSString *)answerjsonRequest stringByReplacingOccurrencesOfString:@"\n" withString:@""]; 

[textvaluesArray addObject:[NSString stringWithFormat:@"%@", answerjsonRequest]]; 

并且输出如下所示。

(
    "{ \"answer\" : \"Hello\", \"qid\" : \"220421824\"}", 
    "{ \"answer\" : \"How are you\", \"qid\" : \"115781136\"}" 
) 

但是,当我将所有在一个像下面的最终输出,

NSString *jsonRequest = [pSr makeJSONObject:[NSArray arrayWithObjects: participantID, (NULL!=textvaluesArray)?textvaluesArray:@"0", [NSString stringWithFormat:@"%d", statusID], subTime, [appDelegate getSessionToken], nil] :[NSArray arrayWithObjects:@"participantId", @"answers", @"statusId", @"submissionTime", @"token", nil] ]; 

The final json result is this. 
{ 
    "submissionTime" : "\/Date(1331566698)\/", 
    "token" : "t_hvYoxifLQhxEKfyw1CAgVtgOfA3DjeB9jZ3Laitlyk9fFdLNjJ4Cmv6K8s58iN", 
    "participantId" : "16371", 
    "answers" : [ 
    "{ \"answer\" : \"Hello\", \"qid\" : \"220421824\"}", 
    "{ \"answer\" : \"Hello\", \"qid\" : \"115781136\"}" 
    ], 
    "statusId" : "0" 
} 

但是,这不是一个我想要什么。我预期的JSON输出是上面提到的最重要的。我尝试了很多方法,但无法做到这一点。有人可以帮助我解决这个问题以获得准确的JSON输出吗?

谢谢!

回答

2

我也遇到了这个问题,并创建了一个快速类别来处理这个问题。

@interface NSString (ReplaceForJSON) 
- (NSString*)replaceEscapedQuotes; 
@end 

@implementation NSString (ReplaceForJSON) 
- (NSString*)replaceEscapedQuotes 
{ 
    NSString* returnVal = [self stringByReplacingOccurrencesOfString:@"\\\"" withString:@"\""]; 

    returnVal = [returnVal stringByReplacingOccurrencesOfString:@"\"{" withString:@"{"]; 

    returnVal = [returnVal stringByReplacingOccurrencesOfString:@"}\"" withString:@"}"]; 

    return returnVal; 
} 
@end 
+0

您能否也请解释您如何致电并解决问题? – Getsy 2012-03-12 17:27:29

+0

'jsonRequest = [jsonRequest replaceEscapedQuotes];' – bdparrish 2012-03-12 17:28:59

+0

很有帮助,非常感谢! – Getsy 2012-03-12 18:33:21