1

When i try to create json from dictionary i get a wrong format with semicolon instead of commas for json

let jsonData = try? JSONSerialization.data(withJSONObject: params)

params is the dictionary. I tried using options: .prettyPrinted but same

result 
{
   "key": "value";
   "key": "value"
}
instead of 
{
   "key": "value",
   "key": "value"
}

I tried to read from a file but same result with semicolon :(

Update this is full code:

let params: Dictionary<String, String> = ["country":"A"
    ,"language":"A"
    ,"query":"some query"
    ,"context": "null"]
let baseURL = "someURL"
let url = URL(string: baseURL)!
var request = URLRequest(url: url)
request.httpMethod = "POST"
do {
    request.httpBody = try JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
    print(try? JSONSerialization.jsonObject(with: request.httpBody!))

} catch let error {
    print(error.localizedDescription)
}

this is the output:

Optional({
    context = null;
    country = A;
    language = A;
    query = "some query";
})

the optional is not the problem but the semicolons

let json = try! JSONSerialization.jsonObject(with: request.httpBody!, options: .allowFragments)

output:

{
    context = null;
    country = A;
    language = A;
    query = "some query";
}
Marian Iconaru
  • 199
  • 4
  • 12

2 Answers2

0

this line solved my problem:

request.addValue("application/json", forHTTPHeaderField: "Content-Type")
Marian Iconaru
  • 199
  • 4
  • 12
-1
let dic = ["2": "B", "1": "A", "3": "C"]


        do {
            //Convert to Data
            let jsonData = try JSONSerialization.data(withJSONObject: dic, options: JSONSerialization.WritingOptions.prettyPrinted)

            //Convert back to string. Usually only do this for debugging
            // just get Json string
            if let JSONString = String(data: jsonData, encoding: String.Encoding.utf8) {
                print(JSONString)
            }
        } catch {
            print(error.localizedDescription)
        }
Abdelahad Darwish
  • 5,969
  • 1
  • 17
  • 35