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

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.

Related

Convert decrypted string into JSON object

After decrypting my response from API i am getting a string "name:DM100, profile:[1,2,4,5]".
How can i convert this to a json object where name is string and profile is an array
i have tried using but getting nil
if let data = testString.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
} catch {
print("JSON Serialization Error :-> \(error.localizedDescription)")
}
}
return nil
}
Your JSON String is not valid. It should look like this:
let testString = "{\"name\":\"DM100\", \"profile\":[1,2,4,5]}"
if let data = testString.data(using: .utf8) {
do {
if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
print(json["name"])
}
}
catch {
print(error.localizedDescription)
}
}
Start and end with curly braces {} and have double quotations around string keys and values.
You can use following code to get the output:
But String must have and valid JSON format first as follows:
let string = "{\"name\":\"DM100\", \"profile\":[1,2,4,5]}"
let data = string.data(using: .utf8)!
do {
if let jsonObj = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? Dictionary<String,Any> {
print(jsonObj)
} else {
print("JSON Error")
}
} catch let error as NSError {
print(error)
}

How to send single quotes in a array as parameter , As i am calling a api using alamofire?

I have to call a api to get a functionality done. In that I have to send a array as a parameter which consists single quotes. But i tried adding a single quote in that , but i am failing miserably getting nil value.
I tried removing the backslash which automatically gets created while trying to send single quotes.
{
"buyerId":"ananth",
"state":"California",
"mobile_no":"5896235966",
"permissionType":"3",
"communityNoArray":"['1441','1643']",
"community_name":"abrakasdabrama"
}
// try this
{
"buyerId":"ananth",
"state":"California",
"mobile_no":"5896235966",
"permissionType":"3",
"communityNoArray":["'12'","'123'"],
"community_name":"abrakasdabrama"
}
Maybe you should create a string from your JSON object. Try with this code:
func jsonToString(json: AnyObject) -> String{
do {
let data1 = try JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions.prettyPrinted)
let convertedString = String(data: data1, encoding: String.Encoding.utf8)
return convertedString!
} catch let myJSONError {
print(myJSONError)
return ""
}
}
let jsonData = [
"buyerId":"ananth",
"state":"California",
"mobile_no": "5896235966",
"permissionType": "3",
"communityNoArray": "['1441','1643']",
"community_name": "abrakasdabrama",
] as [String : Any]
Then you can call it like
let messageString = jsonToString(json: jsonData as AnyObject)
After this, you can send it like a string.
You can convert your param in to Json string by using following method
func convertToJsonString(from object: Any) -> String? {
if let objectData = try? JSONSerialization.data(withJSONObject: object, options: JSONSerialization.WritingOptions(rawValue: 0)) {
let objectString = String(data: objectData, encoding: .utf8)
return objectString
}
return nil
}

Dictionary data was printed in non-JSON style

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"
}

Convert Json string to Json object in Swift 4

I try to convert JSON string to a JSON object but after JSONSerialization the output is nil in JSON.
Response String:
[{\"form_id\":3465,\"canonical_name\":\"df_SAWERQ\",\"form_name\":\"Activity 4 with Images\",\"form_desc\":null}]
I try to convert this string with my code below:
let jsonString = response.result.value
let data: Data? = jsonString?.data(using: .utf8)
let json = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String:AnyObject]
print(json ?? "Empty Data")
The problem is that you thought your jsonString is a dictionary. It's not.
It's an array of dictionaries.
In raw json strings, arrays begin with [ and dictionaries begin with {.
I used your json string with below code :
let string = "[{\"form_id\":3465,\"canonical_name\":\"df_SAWERQ\",\"form_name\":\"Activity 4 with Images\",\"form_desc\":null}]"
let data = string.data(using: .utf8)!
do {
if let jsonArray = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? [Dictionary<String,Any>]
{
print(jsonArray) // use the json here
} else {
print("bad json")
}
} catch let error as NSError {
print(error)
}
and I am getting the output :
[["form_desc": <null>, "form_name": Activity 4 with Images, "canonical_name": df_SAWERQ, "form_id": 3465]]
Using JSONSerialization always felt unSwifty and unwieldy, but it is even more so with the arrival of Codable in Swift 4. If you wield a [String:Any] in front of a simple struct it will ... hurt. Check out this in a Playground:
import Cocoa
let data = "[{\"form_id\":3465,\"canonical_name\":\"df_SAWERQ\",\"form_name\":\"Activity 4 with Images\",\"form_desc\":null}]".data(using: .utf8)!
struct Form: Codable {
let id: Int
let name: String
let description: String?
private enum CodingKeys: String, CodingKey {
case id = "form_id"
case name = "form_name"
case description = "form_desc"
}
}
do {
let f = try JSONDecoder().decode([Form].self, from: data)
print(f)
print(f[0])
} catch {
print(error)
}
With minimal effort handling this will feel a whole lot more comfortable. And you are given a lot more information if your JSON does not parse properly.
I tried the solutions here, and as? [String:AnyObject] worked for me:
do{
if let json = stringToParse.data(using: String.Encoding.utf8){
if let jsonData = try JSONSerialization.jsonObject(with: json, options: .allowFragments) as? [String:AnyObject]{
let id = jsonData["id"] as! String
...
}
}
}catch {
print(error.localizedDescription)
}
I used below code and it's working fine for me. :
let jsonText = "{\"userName\":\"Bhavsang\"}"
var dictonary:NSDictionary?
if let data = jsonText.dataUsingEncoding(NSUTF8StringEncoding) {
do {
dictonary = try NSJSONSerialization.JSONObjectWithData(data, options: [.allowFragments]) as? [String:AnyObject]
if let myDictionary = dictonary
{
print(" User name is: \(myDictionary["userName"]!)")
}
} catch let error as NSError {
print(error)
}
}
static func getJSONStringFromObject(object: Any?) -> String? {
do {
let jsonData = try JSONSerialization.data(withJSONObject: object ?? DUMMY_STRING, options: [])
return String(data: jsonData, encoding: .utf8) ?? DUMMY_STRING
} catch {
print(error.localizedDescription)
}
return DUMMY_STRING
}

Return JSON on output Swift [duplicate]

I have create the next Dictionary:
var postJSON = [ids[0]:answersArray[0], ids[1]:answersArray[1], ids[2]:answersArray[2]] as Dictionary
and I get:
[2: B, 1: A, 3: C]
So, how can I convert it to JSON?
Swift 3.0
With Swift 3, the name of NSJSONSerialization and its methods have changed, according to the Swift API Design Guidelines.
let dic = ["2": "B", "1": "A", "3": "C"]
do {
let jsonData = try JSONSerialization.data(withJSONObject: dic, options: .prettyPrinted)
// here "jsonData" is the dictionary encoded in JSON data
let decoded = try JSONSerialization.jsonObject(with: jsonData, options: [])
// here "decoded" is of type `Any`, decoded from JSON data
// you can now cast it with the right type
if let dictFromJSON = decoded as? [String:String] {
// use dictFromJSON
}
} catch {
print(error.localizedDescription)
}
Swift 2.x
do {
let jsonData = try NSJSONSerialization.dataWithJSONObject(dic, options: NSJSONWritingOptions.PrettyPrinted)
// here "jsonData" is the dictionary encoded in JSON data
let decoded = try NSJSONSerialization.JSONObjectWithData(jsonData, options: [])
// here "decoded" is of type `AnyObject`, decoded from JSON data
// you can now cast it with the right type
if let dictFromJSON = decoded as? [String:String] {
// use dictFromJSON
}
} catch let error as NSError {
print(error)
}
Swift 1
var error: NSError?
if let jsonData = NSJSONSerialization.dataWithJSONObject(dic, options: NSJSONWritingOptions.PrettyPrinted, error: &error) {
if error != nil {
println(error)
} else {
// here "jsonData" is the dictionary encoded in JSON data
}
}
if let decoded = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as? [String:String] {
if error != nil {
println(error)
} else {
// here "decoded" is the dictionary decoded from JSON data
}
}
You are making a wrong assumption. Just because the debugger/Playground shows your dictionary in square brackets (which is how Cocoa displays dictionaries) that does not mean that is the way the JSON output is formatted.
Here is example code that will convert a dictionary of strings to JSON:
Swift 3 version:
import Foundation
let dictionary = ["aKey": "aValue", "anotherKey": "anotherValue"]
if let theJSONData = try? JSONSerialization.data(
withJSONObject: dictionary,
options: []) {
let theJSONText = String(data: theJSONData,
encoding: .ascii)
print("JSON string = \(theJSONText!)")
}
To display the above in "pretty printed" format you'd change the options line to:
options: [.prettyPrinted]
Or in Swift 2 syntax:
import Foundation
let dictionary = ["aKey": "aValue", "anotherKey": "anotherValue"]
let theJSONData = NSJSONSerialization.dataWithJSONObject(
dictionary ,
options: NSJSONWritingOptions(0),
error: nil)
let theJSONText = NSString(data: theJSONData!,
encoding: NSASCIIStringEncoding)
println("JSON string = \(theJSONText!)")
The output of that is
"JSON string = {"anotherKey":"anotherValue","aKey":"aValue"}"
Or in pretty format:
{
"anotherKey" : "anotherValue",
"aKey" : "aValue"
}
The dictionary is enclosed in curly braces in the JSON output, just as you'd expect.
EDIT:
In Swift 3/4 syntax, the code above looks like this:
let dictionary = ["aKey": "aValue", "anotherKey": "anotherValue"]
if let theJSONData = try? JSONSerialization.data(
withJSONObject: dictionary,
options: .prettyPrinted
),
let theJSONText = String(data: theJSONData,
encoding: String.Encoding.ascii) {
print("JSON string = \n\(theJSONText)")
}
}
Swift 5:
let dic = ["2": "B", "1": "A", "3": "C"]
let encoder = JSONEncoder()
if let jsonData = try? encoder.encode(dic) {
if let jsonString = String(data: jsonData, encoding: .utf8) {
print(jsonString)
}
}
Note that keys and values must implement Codable. Strings, Ints, and Doubles (and more) are already Codable. See Encoding and Decoding Custom Types.
Also note that Any does not conform to Codable. It is likely still a good approach to adapt your data to become Codable so that you are making use of Swift typing (especially in the case that you are also going to decode any encoded json), and so that you can be more declarative about the outcome of your encoding.
My answer for your question is below
let dict = ["0": "ArrayObjectOne", "1": "ArrayObjecttwo", "2": "ArrayObjectThree"]
var error : NSError?
let jsonData = try! NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions.PrettyPrinted)
let jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue)! as String
print(jsonString)
Answer is
{
"0" : "ArrayObjectOne",
"1" : "ArrayObjecttwo",
"2" : "ArrayObjectThree"
}
Swift 4 Dictionary extension.
extension Dictionary {
var jsonStringRepresentation: String? {
guard let theJSONData = try? JSONSerialization.data(withJSONObject: self,
options: [.prettyPrinted]) else {
return nil
}
return String(data: theJSONData, encoding: .ascii)
}
}
Sometimes it's necessary to print out server's response for debugging purposes. Here's a function I use:
extension Dictionary {
var json: String {
let invalidJson = "Not a valid JSON"
do {
let jsonData = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted)
return String(bytes: jsonData, encoding: String.Encoding.utf8) ?? invalidJson
} catch {
return invalidJson
}
}
func printJson() {
print(json)
}
}
Example of use:
(lldb) po dictionary.printJson()
{
"InviteId" : 2,
"EventId" : 13591,
"Messages" : [
{
"SenderUserId" : 9514,
"MessageText" : "test",
"RecipientUserId" : 9470
},
{
"SenderUserId" : 9514,
"MessageText" : "test",
"RecipientUserId" : 9470
}
],
"TargetUserId" : 9470,
"InvitedUsers" : [
9470
],
"InvitingUserId" : 9514,
"WillGo" : true,
"DateCreated" : "2016-08-24 14:01:08 +00:00"
}
Swift 5:
extension Dictionary {
/// Convert Dictionary to JSON string
/// - Throws: exception if dictionary cannot be converted to JSON data or when data cannot be converted to UTF8 string
/// - Returns: JSON string
func toJson() throws -> String {
let data = try JSONSerialization.data(withJSONObject: self)
if let string = String(data: data, encoding: .utf8) {
return string
}
throw NSError(domain: "Dictionary", code: 1, userInfo: ["message": "Data cannot be converted to .utf8 string"])
}
}
Swift 3:
let jsonData = try? JSONSerialization.data(withJSONObject: dict, options: [])
let jsonString = String(data: jsonData!, encoding: .utf8)!
print(jsonString)
In Swift 5.4
extension Dictionary {
var jsonData: Data? {
return try? JSONSerialization.data(withJSONObject: self, options: [.prettyPrinted])
}
func toJSONString() -> String? {
if let jsonData = jsonData {
let jsonString = String(data: jsonData, encoding: .utf8)
return jsonString
}
return nil
}
}
The idea of having it as a variable is because then you can reuse it like that:
extension Dictionary {
func decode<T:Codable>() throws -> T {
return try JSONDecoder().decode(T.self, from: jsonData ?? Data())
}
}
Answer for your question is below:
Swift 2.1
do {
if let postData : NSData = try NSJSONSerialization.dataWithJSONObject(dictDataToBeConverted, options: NSJSONWritingOptions.PrettyPrinted){
let json = NSString(data: postData, encoding: NSUTF8StringEncoding)! as String
print(json)}
}
catch {
print(error)
}
Here's an easy extension to do this:
https://gist.github.com/stevenojo/0cb8afcba721838b8dcb115b846727c3
extension Dictionary {
func jsonString() -> NSString? {
let jsonData = try? JSONSerialization.data(withJSONObject: self, options: [])
guard jsonData != nil else {return nil}
let jsonString = String(data: jsonData!, encoding: .utf8)
guard jsonString != nil else {return nil}
return jsonString! as NSString
}
}
using lldb
(lldb) p JSONSerialization.data(withJSONObject: notification.request.content.userInfo, options: [])
(Data) $R16 = 375 bytes
(lldb) p String(data: $R16!, encoding: .utf8)!
(String) $R18 = "{\"aps\": \"some_text\"}"
//or
p String(data: JSONSerialization.data(withJSONObject: notification.request.content.userInfo, options: [])!, encoding: .utf8)!
(String) $R4 = "{\"aps\": \"some_text\"}"
do{
let dataDict = [ "level" :
[
["column" : 0,"down" : 0,"left" : 0,"right" : 0,"row" : 0,"up" : 0],
["column" : 1,"down" : 0,"left" : 0,"right" : 0,"row" : 0,"up" : 0],
["column" : 2,"down" : 0,"left" : 0,"right" : 0,"row" : 0,"up" : 0],
["column" : 0,"down" : 0,"left" : 0,"right" : 0,"row" : 1,"up" : 0],
["column" : 1,"down" : 0,"left" : 0,"right" : 0,"row" : 1,"up" : 0],
["column" : 2,"down" : 0,"left" : 0,"right" : 0,"row" : 1,"up" : 0]
]
]
var jsonData = try JSONSerialization.data(withJSONObject: dataDict, options: JSONSerialization.WritingOptions.prettyPrinted)
let jsonStringData = NSString(data: jsonData as Data, encoding: NSUTF8StringEncoding)! as String
print(jsonStringData)
}catch{
print(error.localizedDescription)
}
This works for me:
import SwiftyJSON
extension JSON {
mutating func appendIfKeyValuePair(key: String, value: Any){
if var dict = self.dictionaryObject {
dict[key] = value
self = JSON(dict)
}
}
}
Usage:
var data: JSON = []
data.appendIfKeyValuePair(key: "myKey", value: "myValue")
2022, swift 5
usage of extensions:
Encode:
if let json = statisticsDict.asJSONStr() {
//your action with json
}
Decode from Dictionary:
json.decodeFromJson(type: [String:AppStat].self)
.onSuccess{
$0// your dictionary of type: [String:AppStat]
}
extensions:
extension Dictionary where Key: Encodable, Value: Encodable {
func asJSONStr() -> String? {
let encoder = JSONEncoder()
if let jsonData = try? encoder.encode(self) {
if let jsonString = String(data: jsonData, encoding: .utf8) {
return jsonString
}
}
return nil
}
}
public extension String {
func decodeFromJson<T>(type: T.Type) -> Result<T, Error> where T: Decodable {
self.asData()
.flatMap { JSONDecoder().try(type, from: $0) }
}
func asData() -> Result<Data, Error> {
if let data = self.data(using: .utf8) {
return .success(data)
} else {
return .failure(WTF("can't convert string to data: \(self)"))
}
}
}
extension JSONDecoder {
func `try`<T: Decodable>(_ t: T.Type, from data: Data) -> Result<T,Error> {
do {
return .success(try self.decode(t, from: data))
} catch {
return .failure(error)
}
}
}
private func convertDictToJson(dict : NSDictionary) -> NSDictionary?
{
var jsonDict : NSDictionary!
do {
let jsonData = try JSONSerialization.data(withJSONObject:dict, options:[])
let jsonDataString = String(data: jsonData, encoding: String.Encoding.utf8)!
print("Post Request Params : \(jsonDataString)")
jsonDict = [ParameterKey : jsonDataString]
return jsonDict
} catch {
print("JSON serialization failed: \(error)")
jsonDict = nil
}
return jsonDict
}

Resources