一尘不染

在iOS中将NSArray of Dictionary转换为JSON数组

json

我需要以数组格式发送一个NSArray到服务器JSON。如何将其转换为JSON。这是NSArray我必须通过的样本。

array([0] => array('latitude'=>'10.010490', 
                  'longitude'=>'76.360779', 
                   'altitude'=>'30.833334', 
                  'timestamp'=>'11:17:23', 
                      'speed'=>'0.00', 
                   'distance'=>'0.00');

[1] => array('latitude'=>'10.010688', 
            'longitude'=>'76.361378', 
             'altitude'=>'28.546305', 
            'timestamp'=>'11:19:26', 
                'speed'=>'1.614', 
             'distance'=>'198.525711')
 )`

所需的格式是这样的

[
  { "latitude":"10.010490",
   "longitude":"76.360779",
    "altitude":"30.833334",
   "timestamp":"11:17:23", 
       "speed":"0.00",
    "distance":"0.00"
  },    
  {
   "latitude":"10.010688",
  "longitude":"76.361378",
   "altitude":"28.546305",
  "timestamp":"11:19:26",
      "speed":"1.614",
   "distance":"198.525711" 
  }
]

有人有解决办法吗?提前致谢。


阅读 217

收藏
2020-07-27

共1个答案

一尘不染

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);
2020-07-27