【问题标题】:How to read JSON.text file to produce data type in swift?如何读取 JSON.text 文件以快速生成数据类型?
【发布时间】:2018-08-22 09:47:16
【问题描述】:

我正在尝试模拟一个网络结果数据并在 JSON.txt 中模拟它,我想执行 json 解析的单元测试,但似乎我总是无法读取 JSON.txt 文件

将要测试的方法:

class Music {


    func parseJSON(data : Data) -> [[String:Any]]? {

        return try? JSONSerialization.jsonObject(with: data, options: []) as! [[String:Any]]
    }
}

这是测试用例

import XCTest
@testable import basicUnitTesting

class musicTests: XCTestCase {


    func testParseJSON() {
        let music = Music()
        let bundle = Bundle(for: type(of: self))
        if let path = bundle.path(forResource: "JSON", ofType: "txt") {
            if let data = try? Data.init(contentsOf: URL.init(fileURLWithPath: path)) {
                let result = music.parseJSON(data: data)

                XCTAssertNotNil(result, "It should not be nil")
                XCTAssertGreaterThan(result!.count, 0, "It should have value, not zero")
            } else {
                XCTFail()
            }

        } else {
            XCTFail()
        }

    }



}

这是错误的截图:

如您所见,路径为 nil,然后测试失败。

这是用于模拟数据的 JSON.txt 中的数据

[{"id":"1","music_url":"http://orangevalleycaa.org/api/media/music/ModernHardRock_45450.wav","name":"现代 Hard Rock","description":"带有酷炫吉他即兴演奏的强大摇滚曲目, 充满活力的常规鼓,紧凑的贝司和吉他独奏。非常适合用于 运动(如拳击)视频、广告 等等","duration":"2:18","image":"http://orangevalleycaa.org/api/media/images/ArtistWorking_059730538.png","thumb":"http://orangevalleycaa.org/api/media/images/thumbs/ArtistWorking_059730538.png","created_by":"ikoliks","file_name_original":"现代 难的 rock_LYNDA_45450.wav"},{"id":"2","music_url":"http://orangevalleycaa.org/api/media/music/AcousticIntro_45687.wav","name":"声学 Intro","description":"带有梦幻般的简短原声吉他介绍, 激发灵感的轻松品质 反射。","duration":"0:57","image":"http://orangevalleycaa.org/api/media/images/BalletInSmoke_054599628.png","thumb":"http://orangevalleycaa.org/api/media/images/thumbs/BalletInSmoke_054599628.png","created_by":"Trevor Lackey","file_name_original":"声学 Intro_LYNDA_45687.wav"},{"id":"3","music_url":"http://orangevalleycaa.org/api/media/music/OptimisticLife_41224.wav","name":"乐观 生活”,“描述”:“乐观的歌曲,那是完美的 需要令人振奋和酷炫的音乐视频的背景 气氛。","duration":"0:30","image":"http://orangevalleycaa.org/api/media/images/BlowingGlass_066874921.png","thumb":"http://orangevalleycaa.org/api/media/images/thumbs/BlowingGlass_066874921.png","created_by":"PremiumAudio","file_name_original":"Optimistic Life_LYNDA_41224. wav"},{"id":"4","music_url":"http://orangevalleycaa.org/api/media/music/TraceyLarvenz_35879.wav","name":"Light and Oxygen","description":"一首起泡、舒缓的曲目,适合 企业、营销和激励 视频。","duration":"3:05","image":"http://orangevalleycaa.org/api/media/images/FireDancers_042981315.png","thumb":"http://orangevalleycaa.org/api/media/images/thumbs/FireDancers_042981315.png","created_by":"Tracey Larvenz","file_name_original":"Tracey Larvenz track_LYNDA_35879.wav"},{"id":"5","music_url":"http://orangevalleycaa.org/api/media/music/ExploreCaliforniaIntro_8773.wav","name":"正在探索 California","description":"合成器和打击乐音轨如 沿着加利福尼亚开车 海岸。","duration":"0:20","image":"http://orangevalleycaa.org/api/media/images/GlassBlownDragon_056473995.png","thumb":"http://orangevalleycaa.org/api/media/images/thumbs/GlassBlownDragon_056473995.png","created_by":"Bryce Poole","file_name_original":"探索加利福尼亚 Intro_LYNDA_8773.wav"},{"id":"6","music_url":"http://orangevalleycaa.org/api/media/music/Aspire_45442.wav","name":"Aspire","description":"\t\rInspiring 原声钢琴、电钢琴、钢片琴演奏的优美曲目 和一些轻的双簧管和单簧管的声音 合唱。","duration":"2:45","image":"http://orangevalleycaa.org/api/media/images/GraffitiArtist_065000861.png","thumb":"http://orangevalleycaa.org/api/media/images/thumbs/GraffitiArtist_065000861.png","created_by":"AudioQuattro","file_name_original":"Aspire_LYNDA_45442.wav "},{"id":"7","music_url":"http://orangevalleycaa.org/api/media/music/BeginningInTheFarm_41245.wav","name":"开始 在农场”,“描述”:“积极而鼓舞人心。梦想、想法和 一种新的和充满的感觉 美丽。","duration":"2:06","image":"http://orangevalleycaa.org/api/media/images/GraphicArtist_052214820.png","thumb":"http://orangevalleycaa.org/api/media/images/GraphicArtist_052214820.png","created_by":"Julio Kladniew","file_name_original":"开始于 Farm_LYNDA_41245.mp3"},{"id":"8","music_url":"http://orangevalleycaa.org/api/media/music/BrightAcousticAmbient_35443.wav","name":"亮 Acoustic Ambient","description":"原声吉他和尤克里里的醇厚 以 12 弦原声吉他为主音轨 乐器。","duration":"3:21","image":"http://orangevalleycaa.org/api/media/images/PleinAirArtist_061873487.png","thumb":"http://orangevalleycaa.org/api/media/images/thumbs/PleinAirArtist_061873487.png","created_by":"Eliosmusic","file_name_original":"明亮的声学 ambient_LYNDA_35443.wav"},{"id":"9","music_url":"http://orangevalleycaa.org/api/media/music/BrothersInArms_46815.wav","name":"兄弟 In Arms","description":"描述战时的主题叙事作品 英雄,胜利和堕落。适合辛酸、情绪化的场景 损失和 悲剧。","duration":"1:15","image":"http://orangevalleycaa.org/api/media/images/SculptorWelding_053783433.png","thumb":"http://orangevalleycaa.org/api/media/images/thumbs/SculptorWelding_053783433.png","created_by":"John Leonard French","file_name_original":"Brothers In Arms_LYNDA_46815.wav"},{"id":"10","music_url":"http://orangevalleycaa.org/api/media/music/BusinessCorporateBackgrounds_41443.wav","name":"企业 企业背景","描述":"积极向上、令人振奋和 鼓舞人心的柔和企业氛围音乐,完美的背景音乐 励志故事、广告、电视广告、品牌的音乐 公司与新闻、科学与发明、建筑与贸易、 技术和教育等等 更多。","duration":"2:57","image":"http://orangevalleycaa.org/api/media/images/SpinningPottery_061544433.png","thumb":"http://orangevalleycaa.org/api/media/images/thumbs/SpinningPottery_061544433.png","created_by":"AZOVMUSIC","file_name_original":"企业背景_LYNDA_41443 .wav"}]

【问题讨论】:

  • txt 文件是否在测试包中,Target Membership 是否已检查?
  • 而不是 TEXT 你的扩展必须是 JSON 类型。干杯。
  • @dahiya_boy 不,没关系。实际上 JSON 是纯文本。
  • @vadian 那么本地json结构文件使用JSON扩展还是TEXT扩展是一样的?
  • 是的,是一样的。如果您正在加载 Data,只要 URL 有效,文件扩展名就无关紧要。

标签: ios json swift unit-testing testing


【解决方案1】:

从错误中可以清楚地看出您的文件未包含在资源路径中 错误行>if let path = bundle.path(forResource: "JSON", ofType: "txt")

所以,问题是您的文件未包含在此处musicTests > Build Phases > Copy Bundle Resources

【讨论】:

    【解决方案2】:

    确保将该 JSON 添加到测试目标中(在文件导航器中选择 JSON 文件,然后在右侧面板中找到“目标成员身份”并验证复选框。

    【讨论】:

      【解决方案3】:

      试试这个

      class Model: NSObject {
      
          static var jsonDict = Dictionary<String,AnyObject>()
      
          func readJson() {
              do {
                  if let file = Bundle.main.url(forResource: "LinqContents", withExtension: "json") {
                      let data = try Data(contentsOf: file)
                      let json = try JSONSerialization.jsonObject(with: data, options: [])
                      if let dict = json as? Dictionary<String,AnyObject> {
                          Model.jsonDict = dict
                      }
                  }
              } catch {
                  print(error.localizedDescription)
              }
          }
      }
      

      【讨论】:

      • 请不要让事情变得更糟。在 Swift 3+ 中,JSON 值永远不会是 AnyObject
      猜你喜欢
      • 2021-03-08
      • 2018-10-04
      • 2020-11-16
      • 2010-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多