1

I have 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"}]"

But I need string in this format \"key\" : value. How to convert this JSON on this format string?

"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\"}]"
Kaushik Makwana
  • 1,329
  • 2
  • 14
  • 24
Stefan
  • 55
  • 8
  • 2
    Possible duplicate of [How to convert JSON to String in ios Swift?](https://stackoverflow.com/questions/36370541/how-to-convert-json-to-string-in-ios-swift) – Arjun Vyas Apr 24 '19 at 09:35
  • Welcome to Stack Overflow! Please follow the guideline before asking your question on Stack Overflow. – Pratik Bhajankar Apr 24 '19 at 09:37
  • 1
    You want JSON Stringified within JSON. So convert it to JSON Data, then convert it into String. Look for `JSONSerialization.data(withJSONObject:options:)` and `String.init(data:encoding:)` – Larme Apr 24 '19 at 10:39

1 Answers1

1

Try below code :-

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
}

In jsonObject pass your json.

Shah Nilay
  • 778
  • 3
  • 21