-2

Is there a solution in Swift to have the value of these 2 key/value pairs in String ?

"ignoredentities":{"actualite":[68533]},
"lastentities":{"actualite":{"uid":3942,"starttime":1504850580},"video":{"uid":4392,"starttime":1504956600}},"count":25}

I want to have 2 String like :

let ignoredentities = "{"actualite":[68533]}"

let lastentities = "{"actualite":
{"uid":3942,
  "starttime":1504850580
},"video":
{"uid":4392,
  "starttime":1504956600
}
},"count":25}"
Mirza Obaid
  • 1,707
  • 3
  • 23
  • 35
Valentin Garcia
  • 143
  • 1
  • 2
  • 10
  • `(NS)JSONSerialization` can transform `(NS)Data` into `(NS)Array`/`(NS)Dictionary` and vice-versa. `(NS)Data` can be transform into `(NS)String` (UTF8) and vice-versa. So yes, it's possible, just look for each transformation one by one on SO. – Larme Sep 14 '17 at 09:03
  • Where is that JSON coming from and in what type is it stored? Have you already parsed it to a Dictionary? – Dávid Pásztor Sep 14 '17 at 09:04
  • @DávidPásztor yes it comes from a Dictionary, I tried String(describing: pagination["lastentities"]) but I got "Optional(<__NSArrayM 0x7c089d40>(\n\n)\n)" – Valentin Garcia Sep 14 '17 at 09:08
  • Possible duplicate of [Convert Dictionary to JSON in Swift](https://stackoverflow.com/questions/29625133/convert-dictionary-to-json-in-swift) – cpt. Sparrow Sep 14 '17 at 09:19
  • @ValentinGarcia so you actually want to store the JSON as a String with all the `{` and `[` symbols instead of properly parsing the JSON and storing it's values such as `actualite = 68533`? – Dávid Pásztor Sep 14 '17 at 09:23
  • @DávidPásztor exactly, I want a String that equals `" {"actualite" : [68533]} "` – Valentin Garcia Sep 14 '17 at 09:35

2 Answers2

1

Try below code

let jsonData = try JSONSerialization.data(withJSONObject: reqDict, options: .prettyPrinted)
                let reqJSONStr = String(data: jsonData, encoding: .utf8)
KavyaKavita
  • 1,581
  • 9
  • 16
0

JSON Dictionary to String:

let data = try JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
let dataString = String(data: data, encoding: String.Encoding.utf8)
print("dataString = \(dataString!)")
Yuyutsu
  • 2,509
  • 22
  • 38