-2

Dictionary to Convert Json String

let dictionary = ["nacho": ["1","2","3"]]
let jsonData = try? JSONSerialization.data(withJSONObject: dictionary, options: [])
let jsonString = String(data: jsonData!, encoding: .utf8)
print(jsonString)

Json String Convert to Dictionary

let jsonString = "{\"nacho\":[\"1\",\"2\",\"3\"]}"
let jsonData = jsonString.data(using: .utf8)
let dictionary = try? JSONSerialization.jsonObject(with: jsonData!, options: .mutableLeaves)
print(dictionary!)
Cœur
  • 37,241
  • 25
  • 195
  • 267

1 Answers1

0

Another instance where the giant ant hits you with the curse of the evil JSONSerialization. You have much more control on the serialisation process if you go the slightly more verbose way of the Codable protocol, but the result will be much easier to handle. Put the following into a quick Playground to see the difference:

import Cocoa

let dictionary = ["nacho": ["1","2","3"]]
let jsonDt = try? JSONSerialization.data(withJSONObject: dictionary, options: [])
let jsonString = String(data: jsonDt!, encoding: .utf8)!
print(jsonString)

let jsonStr = "{\"nacho\":[\"1\",\"2\",\"3\"]}"
let jsonDat = jsonString.data(using: .utf8)
let dict = try? JSONSerialization.jsonObject(with: jsonDat!, options: .mutableLeaves)
print(dict!)

struct Chips: Codable {
    let nacho: [Int]
}

let chip = Chips(nacho: [1, 2, 3])
print(chip)

let chipData: Data?
do {
    chipData = try JSONEncoder().encode(chip)
    print(String(data:chipData!, encoding:.utf8)!)
} catch {
    print(error)
    chipData = nil
}

if let chipData = chipData {
    do {
        let chips = try JSONDecoder().decode(Chips.self, from: chipData)
        print(chips)
    } catch {
        print(error)
    }
}

As you have seen the strings in the first serialisation/deserialization cycle end up being Ints (which I suspect they should have been in the first place), even when they used to be String. JSONSerialization.jsonObject seems to have a mind of its own about which types you will be getting.

In my definition of Chips (for lack of a better name) I could force the use of [Int] which seems more clean. Try out the effect of changing this definition to String. You will have to adapt the initialisation of the object and the serialised String will of course reflect the change. The big advantage over your initial solution with JSONSerialization consists in getting a consistent encode/decode cycle either way, of course with slightly different properties. Choose your preferred way and I am sure your Alamofire will be happy to work with either.

Patru
  • 4,481
  • 2
  • 32
  • 42
  • @BhavikAntala It would be customary (and earn you some points the first time you do) to accept an answer if it solved your problem. Otherwise please post a comment asking for clarification. – Patru May 08 '18 at 03:28
  • Alamofire/swiftJson UserDetail Dictionary Response Convert string to store (Data Setter) func setUserDetail(_ UserDetail: String?) { let personEncodedObject = NSKeyedArchiver.archivedData(withRootObject: UserDetail!) UserDefaults.standard.set(personEncodedObject, forKey: "UserDetail") UserDefaults.standard.synchronize() } - data setter complete @patru – Bhavik Antala May 08 '18 at 06:14
  • but string to Dictinary data not Convert. This is code not work static func userDetail() -> String? { var UserDetail: String? = nil let arcData = UserDefaults.standard.object(forKey: "UserDetail") UserDetail = NSKeyedUnarchiver.unarchiveObject(with: arcData as! Data) as? String return UserDetail } - @Patru – Bhavik Antala May 08 '18 at 06:21
  • Two things are bad style here, first of all you should _not_ put code into comments if it is more than one line, move it to a question. Second your comments do not have anything to do with your initial question. Please ask a different one. You will have more space and improved formatting options to explain what you want to do and why it does not work and, frankly speaking, this is sadly needed. – Patru May 08 '18 at 19:17