1

Не могу найти как сделать json читабельного вида. Допустим есть {"x":5,"b":6} хотелось бы чтобы получилось

{  
"x":5
},
{  
"b":6
}

Ключи заранее не известны

Делаю так

func convertToDictionary(text: String) -> [String: Any]? {
    if let data = text.data(using: .utf8) {
        do {
            return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
        } catch {
            print(error.localizedDescription)
        }
    }
    return nil
}

Приходит:

["x": 5, "b": 6]

1 ответ 1

1

Необходимо сначала строку перевести в json

func convertToDict(text:String) -> [String:Any]? {
if let data = text.data(using: .utf8) {
do{
    return try JSONSerialization.jsonObject(with: data, option: []) as? [String:Any]
}catch{
    print(error.localizedDescription)
   }
 }
 return nil
}

А уже потом в в данный вид

func JSONStringify(value: AnyObject, prettyPrinted: Bool = false) -> String {
if JSONSerialization.isValidJSONObject(value) {

    do{
        let data = try JSONSerialization.dataWithJSONObject(value, options: options)
        if let string = NSString(data: data, encoding: String.Encoding.utf8.rawValue) {
            return string as String
        }
    }catch {

        print("error")

    }

}
return ""
}
1
  • Спасибо, работает
    – user233428
    17 янв 2017 в 17:21

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.