iPhone : JSON message not creating correctly

假装没事ソ 提交于 2020-01-06 05:09:25

问题


I used the following code :

    [dict setObject:[NSString stringWithFormat:@"%d",1] forKey:@"res_id"];


    //[dict setObject:categoryId forKey:@"category"];
    NSArray * values = [cartDict allValues];

    NSString *request1 = [dict JSONRepresentation];
    NSLog(request1);
    NSDictionary *req = [NSDictionary dictionaryWithObject:dict forKey:@""];

    //convert object to data
    NSData *jsonData = [NSData dataWithBytes:[request1 UTF8String] length:[request1 length]];


    //print out the data contents
    NSString *json1 = [[NSString alloc] initWithData:jsonData
                                             encoding:NSUTF8StringEncoding];

    NSLog(@"JSON>>>>>%@",json1);

回答1:


Dude your code is too messy Try this simple example hope you get your idea. It is printing the same thing that you need

NSMutableDictionary *cartDict = [[NSMutableDictionary alloc] init];
[cartDict setObject:[NSString stringWithFormat:@"%@",@"tId"] forKey:@"id"];
[cartDict setObject:[NSString stringWithFormat:@"%@",@"tname"] forKey:@"menuname"];    
[cartDict setObject:[NSString stringWithFormat:@"%@",@"tprice"] forKey:@"price"];
[cartDict setObject:[NSString stringWithFormat:@"%@",@"tquan"] forKey:@"quantity"];
NSArray *array = [NSArray arrayWithObject:cartDict];        
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:[NSString stringWithFormat:@"%@",@"personName"] forKey:@"customerName"];
[dict setObject:[NSString stringWithFormat:@"%@",@"emailid"] forKey:@"cusmailaddress"];
[dict setObject:[NSString stringWithFormat:@"%d",1] forKey:@"res_id"];
[dict setObject:array forKey:@"Order Details"];
NSLog(@"%@",dict);



回答2:


Instead of this

  NSDictionary* info=[NSDictionary dictionaryWithObject:cartDict forKey:@"Order Details"];

Try this. Put your "cartDict" dictionary into array and add that array into dictionary again to achieve your
output



来源:https://stackoverflow.com/questions/9483872/iphone-json-message-not-creating-correctly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!