Converting an NSArray of Dictionaries to JSON array in iOS

后端 未结 8 1094
逝去的感伤
逝去的感伤 2020-12-13 08:09

I need to send an NSArray to the server in the JSON array format. How can I convert it to JSON. This is a sample of my NSArray

相关标签:
8条回答
  • 2020-12-13 08:20

    First You must change you structure into NSDictionary class and NSArray containing NSDictionary objects, then try JSONKit in iOS 5 serialization works better than standard NSJSONSerialization.

    0 讨论(0)
  • 2020-12-13 08:21
    NSDictionary *firstJsonDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                @"10.010490", @"latitude",
                                @"76.360779", @"longitude",
                                @"30.833334", @"altitude",
                                @"11:17:23", @"timestamp",
                                @"0.00", @"speed",
                                @"0.00", @"distance",
                                nil];
    
      NSDictionary *secondJsonDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                @"10.010490", @"latitude",
                                @"76.360779", @"longitude",
                                @"30.833334", @"altitude",
                                @"11:17:23", @"timestamp",
                                @"0.00", @"speed",
                                @"0.00", @"distance",
                                nil];
    
    NSMutableArray * arr = [[NSMutableArray alloc] init];
    
    [arr addObject:firstJsonDictionary];
    [arr addObject:secondJsonDictionary];
    
    NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];
    NSLog(@"jsonData as string:\n%@", jsonString);
    
    0 讨论(0)
  • 2020-12-13 08:22

    Is the service you are calling a RESTful service?

    If so, I'd strongly recommend using RestKit. It does object serialization/deserialization. It also handles all the networking underpinnings. Extremely valuable, and well maintained.

    0 讨论(0)
  • 2020-12-13 08:38

    You can use the build in JSON functions of iOS or use an external lib e.g. JSONKit to convert your data to JSON

    0 讨论(0)
  • 2020-12-13 08:42

    Check this tutorial, JSON in iOS 5.0 was clearly explained (serailization, deserailization).

    0 讨论(0)
  • 2020-12-13 08:43
    #import <JSONKit/JSON.h>
    
    NSArray *array = // Your array here.
    NSString *json = [array JSONString];
    
    NSLog(@"%@", json);
    

    JSONKit performs significantly better than SBJson and others in my own and the author's benchmarks.

    0 讨论(0)
提交回复
热议问题