user3371261 user3371261 - 1 month ago 6
JSON Question

JSON from file Swift 3.0 do not work

I have a problem with JSON, I want to read file JsonData.json using that code(I traied many ways), and always get that error:


Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[NSJSONSerialization dataWithJSONObject:options:error:]: Invalid top-level type in JSON write'


Someone can help me?

func readPropertyList(){
if let path = Bundle.main.path(forResource:"JsonData", ofType: "json"){
//if let url = Bundle.main.url(forResource:"JsonData", withExtension: "json") {
let url: URL = URL(fileURLWithPath: path)
do {
let data: Data = try! Data(contentsOf: url , options: .alwaysMapped)
//let swiftDictionary = try PropertyListSerialization.propertyList(from: data, options: [], format: nil) as! [String]
//list = swiftDictionary
let thisJSON = try! JSONSerialization.data(withJSONObject: data, options: [] )
print(thisJSON)
//print(list)
} catch {
print("lol")
}
}

}


Maybe my, JSON file is wrong but I try verify on http://jsonlint.com and that page say is fine.

{

"Eng":
[
{"Food":
[
{"Avilable":true,
"Meat":
[
{
"Meat":"Mięso",
"Poultry":"Drób",
"Turkey":"Indyk",
"Chicken":"Kurczak",
"Veal":"Cięcina",
"Mutton":"Baranina",
"Venison":"Sarnina",
"Pork":"Wieprzowina",
"Beef":"Wołowina",
"Lamb":"Jagnięcina"
}
],
"Fish":
[
{
"Fish":"ryba",
"Sea food":"Owoce morza",
"Shrimps":"Krewetki",
"Prawns":"Krewetki",
"Mussels":"Małże",
"Crayfish":"Rak słodkowodny",
"Lobster":"Homar",
"Crab":"Krab",
"Tuna":"Tuńczyk",
"Crap":"Karp",
"Eel":"W\u0119gorz",
"Sardine":"Sardynka",
"Salmon":"\u0141oso\u015b",
"Herring":"\u015aled\u017a",
"Cod":"Dorsz",
"Trout":"Pstr\u0105g",
"Bass":"Oko\u0144",
"Fl\u0105dra":"Plaice",
"Pike":"Szczupak"
}
],
"Dairy":
[
{
"Dairy":"Nabia\u0142",
"Dairy products":"Produkty mleczne",
"Milk":"Mleko",
"Cheese":"Ser",
"Cheeses":"Serki",
"Cottage cheese":"Twar\u00f3g",
"Cream":"\u015amierana",
"Yoghurt":"Jogurt",
"Butter":"Mas\u0142o",
"Margarine":"Margaryna"
}
]
}
]
}
]


}

Answer

You're using the wrong API. It's the other way round

let thisJSON = try! JSONSerialization.jsonObject(with: data, options: [] )