Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
436 views
in Technique[技术] by (71.8m points)

iphone - Converting an NSArray of Dictionaries to JSON array in iOS

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 that I have to pass.

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')
 )`

and the required format is like this

[
  { "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" 
  }
]

Any one have solution? Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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:
%@", jsonString);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...