如何在ios

时间:2015-04-22 13:42:31

标签: ios objective-c json

我想以json格式将值发布到服务器,但我坚持使用json格式。我在谷歌搜索了很多,但仍然没有得到确切的格式。

{

    "accountId": "14",
    "order_items": [
        {
        "item_id": "5",
        "quantity": "4 Kg",
        "price": " 69.99"
       },
       {

        "item_id": "6",
        "quantity": "6 Kg",
        "price": " 79.99"
        }
    ]
}

我尝试了以下代码:

NSDictionary *dict=@{@"item_id" : itemide,
                     @"quantity" : @"10",
                     @"price" : @"100"};


NSDictionary *dictionary = @{@"accountId" : @"14",
                             @"order_items" : dict};

NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject:dictionary
                                                           options:0
                                                             error:&error];

if (error)
    NSLog(@"Failure to serialize JSON object %@", error);

NSURL *url = [NSURL URLWithString:@"http://api.lococo.in/orders"];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url
                                                            cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                           timeoutInterval:180.0];

[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"AGDHFGH243SFS" forHTTPHeaderField:@"X-Auth-User"];
[request setValue:@"abcgdg#dg" forHTTPHeaderField:@"X-Auth-Token"];
[request setHTTPBody:postData];

请帮帮我。如何以上述格式获得它?

2 个答案:

答案 0 :(得分:0)

试试这个

NSDictionary *dict=@{@"item_id" : itemide,
                     @"quantity" : @"10",
                     @"price" : @"100"};
NSDictionary *dictionary = @{@"accountId" : @"14",
                             @"order_items" : dict};
NSError *error;
NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];

id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];

答案 1 :(得分:0)

您必须为字典赋值数组。

试试这个:

NSDictionary *dict=@{@"item_id" : itemide,
                    @"quantity" : @"10",
                       @"price" : @"100"};


NSMutableDictionary *dictionary = @{@"accountId" : @"14"};
[dictionary setObject:arrayContainer forKey:@"order_items"];

NSMutableArray *arrayContainer = [NSMutableArray array];
[arrayContainer addObject:dict];