Не удается расшифровать JSON ответ в Swift - PullRequest
0 голосов
/ 06 июля 2019

Я пытаюсь декодировать JSON-ответ с камеры. Но камера отвечает на клавиши с нулевым (это зависит от типа камеры).

Строка результата выглядит следующим образом:

let string =  "{\"id\":1,\"result\":[{\"names\":[\"getAvailableApiList\",\"getShootMode\",\"getSupportedShootMode\",\"getAvailableShootMode\",\"setFlashMode\",\"getFlashMode\",\"getSupportedFlashMode\",\"getAvailableFlashMode\",\"setSelfTimer\",\"getSelfTimer\",\"getSupportedSelfTimer\",\"getAvailableSelfTimer\",\"getSupportedMovieQuality\",\"startLiveview\",\"stopLiveview\",\"actTakePicture\",\"startMovieRec\",\"stopMovieRec\",\"awaitTakePicture\",\"getExposureMode\",\"getSupportedExposureMode\",\"getAvailableExposureMode\",\"setExposureCompensation\",\"getExposureCompensation\",\"getSupportedExposureCompensation\",\"getAvailableExposureCompensation\",\"setFNumber\",\"getFNumber\",\"getSupportedFNumber\",\"getAvailableFNumber\",\"setWhiteBalance\",\"getWhiteBalance\",\"getSupportedWhiteBalance\",\"getAvailableWhiteBalance\",\"getShutterSpeed\",\"getSupportedShutterSpeed\",\"getAvailableShutterSpeed\",\"setIsoSpeedRate\",\"getIsoSpeedRate\",\"getSupportedIsoSpeedRate\",\"getAvailableIsoSpeedRate\",\"actHalfPressShutter\",\"cancelHalfPressShutter\",\"getSupportedProgramShift\",\"getSupportedMovieFileFormat\",\"setContShootingMode\",\"getContShootingMode\",\"getSupportedContShootingMode\",\"getAvailableContShootingMode\",\"setWirelessFlashSetting\",\"getWirelessFlashSetting\",\"getSupportedWirelessFlashSetting\",\"getAvailableWirelessFlashSetting\",\"getApplicationInfo\",\"getEvent\",\"getTemporarilyUnavailableApiList\"],\"type\":\"availableApiList\"},{\"cameraStatus\":\"IDLE\",\"type\":\"cameraStatus\"},null,{\"liveviewStatus\":true,\"type\":\"liveviewStatus\"},null,[],[{\"continuousError\":\"Overheating Warning\",\"isContinued\":false,\"type\":\"continuousError\"},{\"continuousError\":\"Remote Control Not Currently Available\",\"isContinued\":false,\"type\":\"continuousdfError\"}],null,null,null,[],null,null,null,null,null,null,null,{\"currentExposureMode\":\"Aperture\",\"exposureModeCandidates\":[],\"type\":\"exposureMode\"},null,{\"currentSelfTimer\":0,\"selfTimerCandidates\":[0,2,5,10],\"type\":\"selfTimer\"},{\"currentShootMode\":\"still\",\"shootModeCandidates\":[\"still\",\"movie\",\"slow and quick\"],\"type\":\"shootMode\"},null,null,null,{\"currentExposureCompensation\":0,\"maxExposureCompensation\":15,\"minExposureCompensation\":-15,\"stepIndexOfExposureCompensation\":1,\"type\":\"exposureCompensation\"},{\"currentFlashMode\":\"on\",\"flashModeCandidates\":[\"on\",\"rearSync\",\"slowSync\"],\"type\":\"flashMode\"},{\"currentFNumber\":\"3.5\",\"fNumberCandidates\":[\"3.5\",\"4.0\",\"4.5\",\"5.0\",\"5.6\",\"6.3\",\"7.1\",\"8.0\",\"9.0\",\"10\",\"11\",\"13\",\"14\",\"16\",\"18\",\"20\",\"22\"],\"type\":\"fNumber\"},null,{\"currentIsoSpeedRate\":\"250\",\"isoSpeedRateCandidates\":[\"AUTO\",\"50\",\"64\",\"80\",\"100\",\"125\",\"160\",\"200\",\"250\",\"320\",\"400\",\"500\",\"640\",\"800\",\"1000\",\"1250\",\"1600\",\"2000\",\"2500\",\"3200\",\"4000\",\"5000\",\"6400\",\"8000\",\"10000\",\"12800\",\"16000\",\"20000\",\"25600\",\"32000\",\"40000\",\"51200\",\"64000\",\"80000\",\"102400\",\"128000\",\"160000\",\"204800\"],\"type\":\"isoSpeedRate\"},null,null,{\"currentShutterSpeed\":\"1/100\",\"shutterSpeedCandidates\":[],\"type\":\"shutterSpeed\"},{\"checkAvailability\":true,\"currentColorTemperature\":-1,\"currentWhiteBalanceMode\":\"Auto WB\",\"type\":\"whiteBalance\"},null,{\"focusStatus\":\"Not Focusing\",\"type\":\"focusStatus\"},null,null,{\"candidate\":[\"Single\",\"Continuous\"],\"contShootingMode\":\"Single\",\"type\":\"contShootingMode\"},null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null]}"

Каков наилучший способ расшифровки json-ответа?

1 Ответ

0 голосов
/ 06 июля 2019

Используйте JSONSerialization и приведите результат к словарю типа [String: Any]

let data = string.data(using: .utf8)!

do {
    let result = try JSONSerialization.jsonObject(with: data) as! [String: Any]
    //extract info from result
    if let array = result["result"] as? [Any] {
        let item = array.filter( {
            if let dict = $0 as? [String: Any] {
                return dict.contains(where: { $0.key == "currentShootMode"})
            }
            return false
        })
        print(item)
    }
} catch {
    print(error)
}

, чтобы извлечь информацию из переменной item, которую вам нужно снова преобразовать

if let mode = item.first as? [String: Any], let value = mode["currentShootMode"] {
   print(value) 
}
...