iPhone:JSON消息无法正确创建

时间:2012-02-28 14:37:22

标签: iphone ios json nsarray nsdictionary

我使用了以下代码:

    [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);

2 个答案:

答案 0 :(得分:1)

老兄你的代码太乱了 试试这个简单的例子,希望你能得到你的想法它打印的是你需要的东西

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);

答案 1 :(得分:0)

而不是这个

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

试试这个。 将您的“cartDict”字典放入数组并再次将该数组添加到字典中以实现您的目标 输出