如何将JSON字符串快速转换为数组

时间:2019-03-25 09:17:18

标签: ios json swift

我从服务器获取了一个json对象,它实际上是字符串,但看起来像一个数组

["Weekly - Day", "Bi Weekly - Day", "Monthly - Day", "Annual"]

当我打印时,它会像

"[\"Diesel\",\"Gasoline\",\"Toll\",\"Food\",\"Drinks\",\"Cigarettes\",\"Shower\",\"Entertainment\",\"WindShield Washer\",\"Hotel Room\",\"Laundry\",\"Ammunition\",\"Radar Detector\",\"Ticket-Speeding\",\"Ticket-infraction\",\"Brake Fluid\",\"Tie downs\",\"Diesel Anti Gel\",\"Service\",\"Batteries\",\"Flashlight\",\"Wipers\",\"Tires\",\"Radio\",\"Tools\",\"Squeegee\"]"

现在我的问题是,我无法将此字符串转换为数组。

我在做什么

let strng = tempString.replacingOccurrences(of: "[", with: "").replacingOccurrences(of: "]", with: "").replacingOccurrences(of: "\"", with: "")


    let Array = strng.components(separatedBy: ",")

但是我知道这不是正确的方法。当我在stackoverflow中搜索我的问题时,发现:

// Your JSON data:
NSString *colorArray = @"[{ \"color\":\"Red\" },{ \"color\":\"Blue\" },{ \"color\":\"Yellow\"}]";
NSLog(@"colorArray=%@", colorArray);

// Convert to JSON object:
NSArray *jsonObject = [NSJSONSerialization JSONObjectWithData:[colorArray dataUsingEncoding:NSUTF8StringEncoding]
                                                      options:0 error:NULL];
NSLog(@"jsonObject=%@", jsonObject);

// Extract "color" values:
NSArray *tableData = [jsonObject valueForKey:@"color"];
NSLog(@"tableData=%@", tableData);

但是我无法将其转换为swift。任何人都可以帮助我

0 个答案:

没有答案