【问题标题】:Splitting up JSON strings that are in arrays of dictionaries拆分字典数组中的 JSON 字符串
【发布时间】:2015-05-26 02:37:10
【问题描述】:

我有一个使用 Swifty JSON 的函数。它从我的 DataManager 文件中检索数据,该文件从这个 JSON 字符串 http://www.kuakes.com/json/ 中获取信息 我在 tableViewController 文件中的函数将 JSON 分解为我需要的信息,如标题、id、时间等。我的问题是标题条目包含位置和更丰富的比例,我需要将其分解为两个单独的字符串 -一个是规模,一个是位置。 喜欢这个条目:{"id":153355,"title":"mb 4.6 AZERBAIJAN","link":"http://www.emsc-csem.org/Earthquake/earthquake.php?id=443813","来源":"http://www.kuakes.com","north":0,"west":0,"lat":40.799999,"lng":46.919998,"depth":10,"mag":4.6 ,"时间":"2015-05-26 01:20:35 UTC","时间戳":1432603235}

格式化:

{

    "id":153355,
    "title":"mb 4.6 AZERBAIJAN",
    "link":"http:\/\/www.emsc-csem.org\/Earthquake\/earthquake.php?id=443813",
    "source":"http:\/\/www.kuakes.com",
    "north":0,
    "west":0,
    "lat":40.799999,
    "lng":46.919998,
    "depth":10,
    "mag":4.6,
    "time":"2015-05-26 01:20:35 UTC",
    "timestamp":1432603235

}

"mb 4.6 AZERBAIJAN",

func getEarthquakeInfo(completion: (results : NSArray?) ->Void ){


    DataManager.getEarthquakeDataFromFileWithSuccess {
        (data) -> Void in

        let json = JSON(data: data)


        if let JsonArray =  json.array {

            for appDict in JsonArray {
                var ids: String? = appDict["id"].stringValue
                var title: String? = appDict["title"].stringValue
                var time: String? = appDict["time"].stringValue
                var lattitude: String? = appDict["lat"].stringValue
                var longitude: String? = appDict["lng"].stringValue
                var information = AppModel(idEarth: ids, title: title, time: time, lat: lattitude, lng: longitude)
                var title2strings = title!.componentsSeparatedByString(" - ")
                var scale = title2strings[0]
                 var location = title2strings[1] // Error: Array index out of range
                println("\(scale)")
                self.info.append(information)
                completion(results: self.info)
            }


        }

    }

}

如果我在不输入位置的情况下运行程序,它会很好地打印比例。但是,如果某些条目在比例和位置之间没有用“ - ”分隔,它会给我整件事。前任。 M 3.1 希腊南部我想这可能是我在var location = title2strings[1] 收到错误的原因

如果有人可以帮助我解决这个问题,我将不胜感激。

更新:我的最终目标是将所有标题条目分成比例和位置,即使其中一些没有用“-”分隔。我不能遗漏那些没有分开的。如果有人可以建议一种方法来做到这一点,那将有很大帮助。

【问题讨论】:

  • 首先,格式化 JSON。网络上有几个网站可以为您执行此操作,如果您格式化它会更容易理解。

标签: arrays json string swift


【解决方案1】:

我不知道您的 JSON 源中的字符串格式是否一致,但如果一致,您可以尝试以下方法:

let quakes = ["mb 4.6 AZERBAIJAN", "M 3.1 Southern Greece", "M 4.8 - Norwegian Sea"]

let cset = NSCharacterSet.whitespaceCharacterSet()

var results = [(String, String)]()

for quake in quakes {
    var comps = quake.componentsSeparatedByCharactersInSet(cset)
    comps.removeAtIndex(0)
    if comps[1] == "-" {
        comps.removeAtIndex(1)
    }
    let scale = comps[0]
    comps.removeAtIndex(0)
    let loc = " ".join(comps)
    results.append((scale, loc))
}

println(results) // [(4.6, AZERBAIJAN), (3.1, Southern Greece), (4.8, Norwegian Sea)]

【讨论】:

    【解决方案2】:

    问题是,如果 swift 不能将字符串一分为二,那么您将不会在位置 [1] 中得到结果,因为该操作仅返回一个位于位置 [0] 的字符串,例如,如果标题如果“test”被拆分为 int 结果,那么当您尝试读取 result[1] 时,您会得到 result[0] = test 和 result[1] = nil,您会遇到越界错误。

    var title2strings? = title!.componentsSeparatedByString(" - ")
    if let scale = title2strings[0]{
        println(scale)
    } else { println("No value from scale") }
    if let location = title2strings[1]{
        println(location)
    }  { println("No value from location") }
    

    请记住,现在比例和位置是可选的,您需要使用 !强制它打开(不安全)或在访问它之前再次使用if let。

    希望对你有所帮助,祝你好运!

    【讨论】:

    • 我试过了,但在if let scale = title2strings[0]{ 和if let location = title2strings[1] 它给了我:错误:条件中的绑定值必须是可选类型
    • 这样做只会打印在它和它的比例之间有“-”的位置。我的目标是以某种方式获得在比例和位置之间没有“-”的条目。很抱歉,我的问题没有具体说明。
    • 您应该始终在 title2strings[0] 中获取值,即使它没有与 title2strings[1] 中的“-”分开,只有在与“-”分开时才能获得
    【解决方案3】:

    我自己想出了另一种方法。我使用 stringByReplacingOccurrencesOfString 将所有带有“”的标题条目替换为“-”。之后,我就可以拆分所有的字符串了。

    func getEarthquakeInfo(completion: (results : NSArray?) ->Void ){
    
    
        DataManager.getEarthquakeDataFromFileWithSuccess {
            (data) -> Void in
    
            let json = JSON(data: data)
    
    
            if var JsonArray =  json.array {
                JsonArray.removeAtIndex(0)
    
                for appDict in JsonArray {
    
                    var ids: String? = appDict["id"].stringValue
                    var title: String? = appDict["title"].stringValue
                    var time: String? = appDict["time"].stringValue
                    var lattitude: String? = appDict["lat"].stringValue
                    var longitude: String? = appDict["lng"].stringValue
                    let newString = title!.stringByReplacingOccurrencesOfString("  ", withString: " - ", options: NSStringCompareOptions.LiteralSearch, range: nil)
                    var title2strings = newString.componentsSeparatedByString(" - ")
                    var scale = title2strings[0]
                    var location = title2strings[1]
                    var information = AppModel(idEarth: ids, title: title, time: time, lat: lattitude, lng: longitude, scale: scale, location: location)
                    self.info.append(information)
                    completion(results: self.info)
    
    
                 }
            }
    
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-09
      • 1970-01-01
      相关资源
      最近更新 更多