如何将JSON转换为字符串(\“ key \”:value)格式

时间:2019-04-24 09:31:57

标签: ios swift

我有JSON

"bookmarks": "[{"id":633,"serverId":1792,"bookId":39,"bookmarkThemeId":0,"chapterNum":1,"color\":409707362,"verseNum":14,"ssuoBookId":0,"weekNum":0,"dayNum":0,"changeDate":"2000-01-01 00:00:00"},{"id":634,"serverId":1793,"bookId":71,"bookmarkThemeId":0,"chapterNum":5,"color":0,"verseNum":4,"ssuoBookId":0,"weekNum":0,"dayNum":0,"changeDate":"2000-01-01 00:00:00"}]"

但是我需要这种格式的字符串“ \ key \”:值。如何在此格式字符串上转换此JSON

"bookmarks":"[{\"id\":633,\"serverId\":1792,\"bookId\":39,\"bookmarkThemeId\":0,\"chapterNum\":1,\"color\":409707362,\"verseNum\":14,\"ssuoBookId\":0,\"weekNum\":0,\"dayNum\":0,\"changeDate\":\"2000-01-01 00:00:00\"},{\"id\":634,\"serverId\":1793,\"bookId\":71,\"bookmarkThemeId\":0,\"chapterNum\":5,\"color\":0,\"verseNum\":4,\"ssuoBookId\":0,\"weekNum\":0,\"dayNum\":0,\"changeDate\":\"2000-01-01 00:00:00\"}]"

1 个答案:

答案 0 :(得分:1)

尝试以下代码:-

if let jsonString = convertToJsonString(json: jsonObject) {
   print("jsonObjectFromString : \(jsonString)")
}

func convertToJsonString(json: [String: Any]) -> String? {
    do {
        let jsonData = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
        return String(data: jsonData, encoding: .utf8)
    } catch {
        print(error.localizedDescription)
    }
    return nil
}

jsonObject 中传递您的json。