Dictionary data was printed in non-JSON style - ios

I have a dictionary which I convert to JSON but when I print it out I have back slashes which makes it difficult to get it as NSDictionary.
Below is my code:
let postParameters = ["action":"check","msis":"343","username":"username,"os":"ios"]
Then I use postParameters trying to convert to JSON.
if let jsonParameters = try? JSONSerialization.data(withJSONObject: postParameters, options: .prettyPrinted) {
let theJSONText = String(data: jsonParameters,encoding: String.Encoding.utf8)
print("JSON string = \(theJSONText)")
}
Now when I print out the JSON, it comes formatted as next:
JSON string = Optional("{\n \"action\" : \"check\",\n \"os\" : \"ios\",\n \"msis\" : \"343\",\n \"username\" : \"username\"\n}")
Now my question is how should I convert my dictionary to have a JSON with no backslash and \n.

If you rewrite your code to use optional binding to unwrap your theJSONText string, it works as expected:
if let jsonParameters = try? JSONSerialization.data(withJSONObject: postParameters, options: .prettyPrinted),
let theJSONText = String(data: jsonParameters, encoding: .utf8) {
print("JSON string = \(theJSONText)")
}
That displays:
JSON string = {
"os" : "ios",
"msis" : "343",
"action" : "check",
"username" : "username"
}

Related

How do I break down a key value pair into a JSON string in Swift?

Given a key value pair such as "a.b.c.d" = "e", how can I get the following JSON string:
{
"a": {
"b": {
"c": {
"d": "e"
}
}
}
}
You could construct a dictionary hierarchy and then convert that to a JSON string.
Given a
key consisting of a dot (.) separated list of path elements
and a value,
you can build your dictionary object as follows:
var jsonObject: [String: Any]
var path = key.split(separator: ".").map { String($0) }
let lastKey = path.popLast()!
jsonObject = [lastKey: value]
for element in path.reversed() {
jsonObject = [element: jsonObject]
}
Then you can can get a pretty printed version (as in your example above) as follows:
let jsonData = try! JSONSerialization.data(withJSONObject: jsonObject, options: [.prettyPrinted])
let encoded = String(data: jsonData, encoding: .utf8)!
To get a compact (non-pretty) version, omit the .prettyPrinted option (but leave the array brackets).
let jsonData = try! JSONSerialization.data(withJSONObject: jsonObject, options: [])
let encoded = String(data: jsonData, encoding: .utf8)!
Here's the whole thing packaged into a function:
func jsonFromKeyValue(key: String, value: String) -> String {
var jsonObject: [String: Any]
var path = key.split(separator: ".").map { String($0) }
let lastKey = path.popLast()!
jsonObject = [lastKey: value]
for element in path.reversed() {
jsonObject = [element: jsonObject]
}
let jsonData = try! JSONSerialization.data(withJSONObject: jsonObject, options: [.prettyPrinted])
let encoded = String(data: jsonData, encoding: .utf8)!
return encoded
}
Try it with:
let jsonObject = jsonFromKeyValue(key: "a.b.c.d", value: "e")
print(jsonObject)

How to convert JSON to string ( \"key\" : value ) format

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\"}]"
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.

Is there any way to encode the dictionary into JSON form using JSONEncoder

Here the Dictionary
struct Person : Codable {
let name : String?
let city : String?
let age : Int?
}
let dic : [String : Any] =
["name":"Manna","city" : "Rangpur", "age": 18,
"name":"Munna","city" :"Dhaka","age":19,
"name":"Shaon","city" :"Rangpur","age":11,
"name":"Limon","city" :"Tangail","age":15,
"name":"Lalon","city" :"Rangpur","age":18,
"name":"Rakib","city" :"Dhaka","age":15,
"name":"Mum","city" :"Rangpur","age":18,
"name":"Man","city" :"Bogura","age":12,
"name":"Limon","city" :"Tangail","age":18]
// let manna = Person(name: "Manna", city: "Rangpur", age: 18)
// Here i want to use the dictionary
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
do {
let data = try encoder.encode(manna)
print(String(data: data, encoding: .utf8)!)
} catch {
print("error : \(error.localizedDescription)")
}
trying to encode this dictionary just like json file as an output using JSONEncoder
First of all your dictionary is wrong because dictionary doesn't contains same key.
You can present it as like array of dictionary
let dic : [[String : Any]] = [["name":"Manna", "city" : "Rangpur", "age": 18],
["name":"Munna","city" :"Dhaka","age":19,],
["name":"Shaon","city" :"Rangpur","age":11,],
["name":"Limon","city" :"Tangail","age":15,],
["name":"Lalon","city" :"Rangpur","age":18,],
["name":"Rakib","city" :"Dhaka","age":15,],
["name":"Mum","city" :"Rangpur","age":18,],
["name":"Man","city" :"Bogura","age":12,],
["name":"Limon","city" :"Tangail","age":18]]
Now you can convert this array of dictionary into JSON as like below
if let data = try? JSONSerialization.data(withJSONObject: dic, options: JSONSerialization.WritingOptions.prettyPrinted) {
print(data.count)
let json = String(data: data, encoding: String.Encoding.utf8)
print(json ?? "")
}

Error : Cannot convert value of type 'String.Type' to expected dictionary key type 'String'

The following is my code where in the last line of the code I am getting an error as mentioned in the title. what should i do??
let jsonObject: [Any] = [
[
"userName": "meUser",
"emailID": "meUser#gmail.com",
"phoneNumber": "7290407896",
"fiatCurrency": ["currencyCode" : "INR"],
"countryCode": "IND",
]
]
let jsonData = try! JSONSerialization.data(withJSONObject: jsonObject, options: JSONSerialization.WritingOptions.prettyPrinted)
let jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue)! as String
print(jsonString)
User.saveUser(userData: [String: (jsonString)!])
The error is pretty clear. You are using a Swift Type String instead of an instance of String to store your value jsonString.
You should be using a String key which you will use later to retrieve your value.
if let jsonString = String(data: jsonData, encoding: .utf8) {
User.saveUser(userData: ["jsonString": jsonString])
}
Note: Use String instead of NSString in Swift (the same method is available for String) and safely unwrap your jsonString.
The error is in this line:
User.saveUser(userData: [String: (jsonString)!])
Here, you have provided dictionary key = String, String is a type in Swift, you can't use it as key for dictionary. You need to provide a value which is of type String not String itself.
String is Struct type in swift which is used in the last line,
User.saveUser(userData: [String: (jsonString)!])
Use some string object rather than class name. Such as:
User.saveUser(userData: ["your_key_name": (jsonString)!])
And you can updated your code as:
let jsonData = try? JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted)
if let json = jsonData, let jsonString = String(data: json, encoding: .utf8) {
print(jsonString)
User.saveUser(userData: ["key_name": jsonString])
}

What is the easiest way to create readable JSON string?

I want to draw formatted JSON string with new lines and tabs (or spaces).
But the code below yields string as long one lined text.
let resultString = String(data: response.data, encoding: .utf8)
Is there any default method to create multiline JSON string?
You can use prettyPrinted option of JSONSerialization
do {
let json = try JSONSerialization.jsonObject(with: response.data, options: []) as! [String: AnyObject]
let formattedJson = try JSONSerialization.data(withJSONObject: json, options:JSONSerialization.WritingOptions.prettyPrinted )
if let formattedString = String(data: formattedJson, encoding: .utf8) {
print(formattedString)
}
} catch {
print("Error: \(error)")
}
As for the JSONEncoder introduced in Swift 4, there is a prettyPrinted option:
struct Foo: Codable {
var bar: String
var baz: Int
}
let foo = Foo(bar: "gfdfs", baz: 334)
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted // This makes it formatted as multiline
let data = try encoder.encode(foo)
print(String(data: data, encoding: .utf8)!)
The output is:
{
"bar" : "gfdfs",
"baz" : 334
}

Resources