0

我想JSON格式在我app.my JSON是這樣的:如何發送JSON格式的POST方法

{ 
    user: { 
     id: 2 
    }, 
    items: [ 
     { 
     id: 2, 
     num: 3 
     } 
    ] 
} 

我可以做JSON格式與此代碼:

NSMutableDictionary *json = [[NSMutableDictionary alloc]init]; 

    NSMutableDictionary *users = [[NSMutableDictionary alloc]init]; 
    [users setObject:@"2" forKey:@"id"]; 

    NSMutableDictionary *item = [[NSMutableDictionary alloc]init]; 
    [item setObject:@"22" forKey:@"id"]; 
    [item setObject:@"33" forKey:@"num"]; 

    NSMutableArray *itemArray = [[NSMutableArray alloc]initWithObjects:item, nil]; 

    [json setObject:users forKey:@"user"]; 
    [json setObject:itemArray forKey:@"items"]; 

    NSLog(@"%@",json); 

    NSError *error = nil; 
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:json 
                 options:0 
                 error:&error]; 

現在我想知道這是真的嗎? 如果這是真的,請指導我如何發送此JSONPOST方法的網址?

這個代碼發送JSON

NSURL *url = [NSURL URLWithString: @"http://192.168.1.193/deliapi/order/new?token=absc"]; 

    NSString *postLength = [NSString stringWithFormat:@"%d",[jsonData length]]; 
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 

    [request setURL:url]; 

    [request setHTTPMethod:@"POST"]; 
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 
    [request setHTTPBody:jsonData]; 
    NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self]; 

    [conn start]; 


    if(conn) 
    { 
     NSLog(@"Connection Successful"); 
    } 
    else 
    { 
     NSLog(@"Connection could not be made"); 
    } 
+0

在你最後一個問題中,你說*「我知道如何使用POST方法發送數據」* :) – 2014-09-06 05:29:14

+0

@MartinR你沒錯,但沒有工作,現在我很困惑。我想知道如何將NSMutableDictionary轉換爲JSON格式? – user3599133 2014-09-06 05:40:23

+0

你已經做到了。 'jsonData'包含JSON格式的數據。 - 如果它不工作,那麼你必須添加更多的信息。你如何發送數據,你會得到什麼錯誤,... – 2014-09-06 05:45:41

回答

0

我的朋友你的代碼是正確的!你應該確定應用程序/ JSON的HeaderField:

寫這樣的代碼:

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; 

我希望幫助你!

相關問題