2014-06-06 174 views
-2

鍵使用此代碼來獲取和分析:解析JSON沒有SWIFT

func getJSON(urlToRequest: String) -> NSData 
{ 
    return NSData(contentsOfURL: NSURL(string: urlToRequest)) 
} 
func parseJSON(inputData: NSData) -> NSDictionary 
{ 
    var error: NSError? 
    var boardsDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(inputData, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary 
    return boardsDictionary 
} 
    var parsedJSON = parseJSON(getJSON("url")) 

println(parsedJSON)結果:

{ 
message = ""; 
result =  (
      { 
     BC = B; 
     BCL = Bbb; 
     C = "2014-02-13T00:00:00"; 
     IA = 1; 
     MC = L; 
     MCL = Lll; 
     MN = "B-L"; 
     MS = "165"; 
    }, 
      { 
     BC = B; 
     BCL = Bbb; 
     C = "2014-02-13T00:00:00"; 
     IA = 1; 
     MC = E; 
     MCL = Eee; 
     MN = "B-E"; 
     MS = "654"; 
    }, 
      { 
     BC = B; 
     BCL = Bbb; 
     C = "2014-02-13T00:00:00"; 
     IA = 1; 
     MC = D; 
     MCL = Ddd; 
     MN = "B-D"; 
     MS = "864"; 
    }, 
); 
success = 1; 
} 

println(parsedJSON["result"])結果:

{ 
     BC = B; 
     BCL = Bbb; 
     C = "2014-02-13T00:00:00"; 
     IA = 1; 
     MC = L; 
     MCL = Lll; 
     MN = "B-L"; 
     MS = "165"; 
    }, 
      { 
     BC = B; 
     BCL = Bbb; 
     C = "2014-02-13T00:00:00"; 
     IA = 1; 
     MC = E; 
     MCL = Eee; 
     MN = "B-E"; 
     MS = "654"; 
    }, 
      { 
     BC = B; 
     BCL = Bbb; 
     C = "2014-02-13T00:00:00"; 
     IA = 1; 
     MC = D; 
     MCL = Ddd; 
     MN = "B-D"; 
     MS = "864"; 
    }, 

println(parsedJSONlS["result"]!["MCL"])給 「無」

如何從每組中提取MCL值?我可以通過索引訪問值嗎?

+0

轉到json.org所和學習JSON語法 - 只需要5-10分鐘。 「結果」是一個數組。 –

回答

0

它看起來像parsedJSONlS [「結果」]會給你一個字典數組。你可以這樣做:

var array = parsedJSONlS["result"] 
array[0]["MCL"] 
// or 
var dictionary = array[0] as Dictionary 
println(dictionary["MCL"]) 

這當然只是給你的結構的想法,你必須創建該陣列一個循環,並抓住所有的字典,並提取它們的值。

0

您應該在這裏考慮選項:從字典中檢索值可能會返回nil。因此,採取從你的字典每MCL值,並把它們的元組數組的索引:

func retrieveMCL(index : Int, value : Dictionary<String, String>) -> (Int,String)? 
    { 
     switch value["MCL"] { 
     case .Some(let mclValue): return (index, mclValue) 
     default: return nil 
     } 
    } 

    // This mimics your results from JSON 
    let results = ["result":[["MCL":"Eee"],["MCL":"Ddd"]]] 
    var mclArray : Array<(Int,String)> = [] 

    if let resultsArray = results["result"] 
    { 
     for (index,value) in enumerate(resultsArray){ 
      if let mclTupple = retrieveMCL(index, value) { 
       mclArray += mclTupple 
      } 
     } 
    }