Home > OS >  Swift - Convert nested JSON to dictionary
Swift - Convert nested JSON to dictionary

Time:10-12

How do I get a dictionary for all levels of nested json data?

JSON data:

{"places":[
    {"name":"東京","date":"2005/03/02","transport":"新幹線"},
    {"name":"北海道","date":"2006/04/06","transport":"飛行機"}
    ],
 "no_of_person":"4",
 "package_name":"日本最高"
} 

My code:

let response: String = "{\"places\":[{\"name\":\"東京\",\"date\":\"2005/03/02\",\"transport\":\"新幹線\"},{\"name\":\"北海道\",\"date\":\"2006/04/06\",\"transport\":\"飛行機\"}],\"no_of_person\":\"4\",\"package_name\":\"日本最高\"}"
    
let jsonObj = response.data(using: .utf8)!
do {
    let items = try JSONSerialization.jsonObject(with: jsonObj, options: []) as! Dictionary<String, Any>
    print(items)    
} catch {
    print(error)
}

My terminal output:

["package_name": 日本最高, "places": <__NSArrayI 0x280fde800>(
{
    date = "2005/03/02";
    name = "\U6771\U4eac";
    transport = "\U65b0\U5e79\U7dda";
},
{
    date = "2006/04/06";
    name = "\U5317\U6d77\U9053";
    transport = "\U98db\U884c\U6a5f";
}
)
, "no_of_person": 4]

As shown in the terminal output above,

  1. How do I get "places" as a Dictionary instead of an Array?
  2. Also how can I keep the Japanese text as it is, like the one in the "package_name"?

EDIT: Correction: How do I get "places" as an array of Dictionaries?

CodePudding user response:

I think this will help you if you would like to use jsondecoder.

struct SampleData: Codable {
    let places: [Place]
    let no_of_person: String
    let package_name: String
}

struct Place: Codable {
    let name: String
    let date: String
    let transport: String
}

do {
    var dataDecoded = try JSONDecoder().decode(SampleData.self, from: data)
} catch {
    print("uppsss there is something wrong in decoding: \(error)")
}
  • Related