swift NSJSONSerialization json解析
以下是解析、生成方法
func jsonParse(){
/****************************************** 解析json类型 **************************************/
let jsonFile = NSBundle.mainBundle().pathForResource("JsonParseFile", ofType: "geojson")
let jsonData = NSData.dataWithContentsOfMappedFile(jsonFile!) as NSData
var errorRead:NSError?
var jsonParse = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableLeaves, error: &errorRead) as NSDictionary
if errorRead==nil {
let itemCount = jsonParse.objectForKey("ItemCount") as NSString
println("数据总数 : \(itemCount)")
let itemArray = jsonParse.objectForKey("Info") as NSArray
println("当前数组 : \(itemArray.count)")
let dataArray = jsonParse.objectForKey("Info") as NSArray
for manDic in dataArray{
let name = manDic.objectForKey("Name") as NSString
println("数据数组 : \(name)")
}
}else{
println("json不合法,解析失败")
}
/****************************************** 转化成json类型 **************************************/
let writeJsonArray1 = ["1","2","3"]
let writeJsonArray2 = ["4","5","6"]
let writeJsonDictory = ["数组1":writeJsonArray1,"数组2":writeJsonArray2]
let jsonFormater = NSJSONSerialization.isValidJSONObject(writeJsonDictory)
if jsonFormater {
println("是标准json格式")
}else{
println("非标准json格式")
}
var errorWrite:NSError?
var jsonWriteData = NSJSONSerialization.dataWithJSONObject(writeJsonDictory, options: NSJSONWritingOptions.PrettyPrinted, error: &errorWrite)
var lastParse = NSString(data: jsonWriteData!, encoding: NSUTF8StringEncoding)
println("转化成json类型 \n\(lastParse)")
}