Converting String to [String : Any] - ios

I have a string that defines an object like so:
let object = """
{
"id": 59d75ec3eee6c20013157aca",
"upVotes": NumberLong(0),
"downVotes": NumberLong(0),
"totalVotes": NumberLong(0),
"timestamp" : "\(minutesAgo(1))",
"caption": "hello",
"username": "hi",
"commentsCount": NumberLong(0),
"lastVotingMilestone": NumberLong(0),
"type": "Text"
}
"""
I need to convert it into the format [String : Any] but I'm not sure how to do this. In the past I have put the string into a json file and loaded that like this:
let data = NSData(contentsOfFile: file)
let json = try! JSONSerialization.jsonObject(with: data! as Data, options: [])
let dict = json as! [String: Any]
Anyone know how I can do this? Thanks!

Why are you doing it the complicated way in the first place? You want a dictionary, so define a dictionary.
let dict: [String: Any] = [
"id": "59d75ec3eee6c20013157aca",
"upVotes": 0,
"downVotes": 0,
...
]
Anyway, the NumberLong(0) isn't valid JSON, so that isn't going to work anyway.

In Swift 4, you can use JSONDecoder API to decode JSON data, i.e.
let object = """
{
"id": 59d75ec3eee6c20013157aca",
"upVotes": NumberLong(0),
"downVotes": NumberLong(0),
"totalVotes": NumberLong(0),
"timestamp" : "Some Value",
"caption": "hello",
"username": "hi",
"commentsCount": NumberLong(0),
"lastVotingMilestone": NumberLong(0),
"type": "Text"
}
"""
if let data = object.data(using: .utf8)
{
if let dict = try? JSONDecoder().decode([String: Any].self, from: data)
{
}
}

Related

How to display NsMutable Array

When decoding JSON response from webservice I get an ouput saying:
["dataresult": <__NSArrayM 0x1c0243090>( )]
How to display / decode this NSArrayM
Any help on this would be appreciated
Below is the code
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
print("JSON yet to be parsed")
if let parseJSON = json {
let myBoard = parseJSON["message"] as! [String:Any]
print("JSON parsed successfully !")
print(myBoard)
if let refResults = myBoard["dataresult"] as? [[String:String]]{
let valueArray = refResults.map {$0["Success"]!}
self.Contact = valueArray
print(self.Contact)
}
Response from the Web Service:
"message": {
"dataresult": [
{
"Success": "Success",
"OwnerName": "test shop",
"mobileno": "1231231231",
"landline": "",
"managername": "acsd acfacaf",
"managerContact": "",
"email": "test#gmail.com",
"website": "",
"address": "gggysgyysusisss",
"city": "hgyggg",
"area": "fgatsbsuhsushsu",
"pincode": "123123",
"rentowned": "Leased",
"homedelivary": "Yes",
"working_start_time": "10.00 am",
"working_end_time": "7.30 pm",
"pwd": "123123"

How to pasre JSON (dictionary and array) using the new Swift 3 and Alamofire

Can any one suggest and send me sample code for fetching JSON response. Few APIs I am getting data in the form of the NSDictionary and few APIs I am getting data in the form of NSArray.
This is my API request with Alamofire.
APIManager.sharedInstance.getTeacherProfileDataFromURL(){(userJson)-> Void in
let swiftyJsonVar = JSON(userJson)
print("userJson userJson userJson userJson",userJson)
print("swiftyJsonVar",swiftyJsonVar)
}
1) API WITH JSON ARRAY OF DATA
{
"status": 1,
“student”: [
{
"name": "Sprouse",
"subject": [
“english”
],
"personal_email": "",
"school_email": "cole.sprouse483#demo.in",
"phone": "9665478544",
"class_teacher": false,
"image": "/assets/default_male.png"
},
{
"name": “elen”,
"subject": [
"Social Science"
],
"personal_email": "",
"school_email": "elena.gilbert564#demo.in",
"phone": "9066260799",
"class_teacher": false,
"image": "/assets/default_female.png"
},
],
"message": "Details fetched successfully."
}
2) ANOTHER API WITH JSON DICTIONARY OF DATA
{
"status": 1,
"dashboard": {
"announcement": [
{
"title": "Independence Day Celebration",
"posted_on": "13 August, 2017"
}
],
"student": {
"attendance_percent": 100,
"assignment": [
{
"title": "Alphabets in HINDI",
"end_date": "13/09/2017",
"subject": "Hindi",
"teacher_name": "Bonnie Bennette"
}
],
"leave_apply": 13
},
"image": "/system/images/86/j1f9DiJi_thumb.jpg?1504593436"
},
"message": "Details fetched successfully."
}
1) API WITH JSON ARRAY OF DATA
let swiftyJsonVar = JSON(userJson)
let array : [[String : String]] = swiftyJsonVar["student"]
This will give you an array of dictionaries or key-values of student.
Further you can get another value from the array like that
let name : String = array[0]["name"]
2) ANOTHER API WITH JSON DICTIONARY OF DATA
let swiftyJsonVar = JSON(userJson)
let dictionary : [[String : String]] = swiftyJsonVar["dashboard"]
This will give you an array of dictionary or key-value of dashboard.
let array : [[String : String]] = dictionary["announcement"]
This will give you the array of announcement and next you can get the further values like this
let name : array = array[0]["title"]
i have resolved my issue long back , posting lately this is my answer it may helpful for other thats why i am posting here.
if data is in the form of array.
DispatchQueue.main.async {
TeacherAPIManager.sharedInstance.FetchTeacherStudentAttendanceDataFromURL(){(attendanceJson)-> Void in
print("observationInfo --",attendanceJson)
let swiftyAttendanceJsonVar = JSON(attendanceJson)
let observation = swiftyAttendanceJsonVar["list"].rawString()!
let jsonData = observation.data(using: .utf8)!
let array = try? JSONSerialization.jsonObject(with: jsonData, options: []) as! Array< Any>
for observationVar in array!{
let totlDic = NSMutableDictionary()
let dic = observationVar as! Dictionary<String,Any>
}
}
if data is in the form of dictionary. just replace this below of line code in above function array line.
let dictionary = try? JSONSerialization.jsonObject(with: jsonData, options: []) as! Dictionary<String, Any>

How to convert JSON String to JSON Object in swift?

I trying to generate JSON Object and convert that to JSON String and that process is Successfully placed. But my real problem rises when I try to convert JSON String to JSON Object. When I try I get nil as result.
func generateJSONObject() {
let jsonObject = createJSONObject(firstName: firstName[0], middleName: middleName[0], lastName: lastName[0], age: age[0], weight: weight[0])
print("jsonObject : \(jsonObject)")
let jsonString = jsonObject.description // convert It to JSON String
print("jsonString : \(jsonString)")
let jsonObjectFromString = convertToDictionary(text: jsonString)
print("jsonObjectFromString : \(String(describing: jsonObjectFromString))")
}
createJSONObject func
// JSON Object creation
func createJSONObject(firstName: String, middleName: String, lastName: String, age: Int, weight: Int) -> [String: Any] {
let jsonObject: [String: Any] = [
"user1": [
"first_name": firstName,
"middle_name": middleName,
"last_name": lastName,
"age": age,
"weight": weight
]
]
return jsonObject
}
convertToDictionary func
func convertToDictionary(text: String) -> [String: Any]? {
if let data = text.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
} catch {
print(error.localizedDescription)
}
}
return nil
}
Logs
When I print JSON Object I get
jsonObject : ["user1": ["age": 21, "middle_name": "Lazar", "last_name": "V", "weight": 67, "first_name": "Alwin"]]
When I print JSON String I get
jsonString : ["user1": ["age": 21, "middle_name": "Lazar", "last_name": "V", "weight": 67, "first_name": "Alwin"]]
Convert JSON String to JSON Object I get below error
The data couldn’t be read because it isn’t in the correct format.
jsonObjectFromString : nil
I don't know why this happening. I want to convert JSON String to JSON Object and I want to parse the JSON.
based on discussion
import Foundation
let firstName = "Joe"
let lastName = "Doe"
let middleName = "Mc."
let age = 100
let weight = 45
let jsonObject: [String: [String:Any]] = [
"user1": [
"first_name": firstName,
"middle_name": middleName,
"last_name": lastName,
"age": age,
"weight": weight
]
]
if let data = try? JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted),
let str = String(data: data, encoding: .utf8) {
print(str)
}
prints
{
"user1" : {
"age" : 100,
"middle_name" : "Mc.",
"last_name" : "Doe",
"weight" : 45,
"first_name" : "Joe"
}
}
Json has to be in Array or Dictionary, it can't be only string so to create a jsonstring first you need to convert to Data format and then convert to String
func generateJSONObject() {
let jsonObject = createJSONObject(firstName: "firstName", middleName: "middleName", lastName: "lastName", age: 21, weight: 82)
print("jsonObject : \(jsonObject)")
if let jsonString = convertToJsonString(json: jsonObject), let jsonObjectFromString = convertToDictionary(text: jsonString) {
print("jsonObjectFromString : \(jsonObjectFromString)")
}
}
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
}

Unable to convert this JSON to a string

Please see below the json output
{
"queryLogs" : [
{
"status" : "false",
"query" : {
"contents" : {
"updated" : "",
"id" : 1488199579,
"created" : "",
"patient_count" : 60,
"isactive" : "1",
"status_id" : 0,
"starttime" : "",
"queue_status_id" : 0,
"date_consult" : ""
},
"conditions" : "{}"
},
"tableName" : "consultation",
"type" : "I",
"logId" : {
"id" : "261489537666",
"doctorId" : "100"
}
}
]
}
Need to convert above json into below format
{"queryLogs":[{ "logId":{"id":"76148951287","doctorId":"100"},
"tableName":"queue", "type":"I", "query":"{ \"contents\":{
\"patient_name\":\"queryLog Test\", \"status_id\":1,
\"queue_no\":\"6\", \"isactive\":1, \"id\":\"148956612\",
\"mobile\":\"9567969610\", \"updated\":\"2017-03-15 11:31:26
GMT+05:30\", \"created\":\"2017-03-15 11:31:26 GMT+05:30\",
\"consultation_id\":\"1495085636\"}, \"conditions\":{}
}","status":"false"}]}
First code is what i get when i convert the JSON, But how can i get the JSON like the second code.
i used below code to get the first output.
var f = ["queryLogs":[["status":"false","tableName":"consultation","type":"I","logId":ids,"query":logfile]]] as [String : Any]
let JSON = try? JSONSerialization.data(withJSONObject: f,
options:.prettyPrinted)
if let content = String(data: JSON!, encoding:
String.Encoding.utf8) {
print(content)
}
If you want response like that then you need to also make JSON string for your logfile dictionary also.
What you can do is make one extension of Dictionary, so that no need to write same code of JSONSerialization at every place.
extension Dictionary where Key: ExpressibleByStringLiteral {
var jsonString: String? {
guard let data = try? JSONSerialization.data(withJSONObject: self),
let string = String(data: data, encoding: .utf8) else {
return nil
}
return string
}
}
Now use this extension to get JSON string from your dictionaries.
let id‌​s = ["id" : "261489537666", "doctorId" : "100"]
let logfile = [
"contents" : [
"updated" : "",
"id" : 1488199579,
"created" : "",
"patient_count" : 60,
"isactive" : "1",
"status_id" : 0,
"starttime" : "",
"queue_status_id" : 0,
"date_consult" : ""
],
"conditions" : "{}"
] as [String : Any]
if let queryLogString = logfile.jsonString {
let f = ["queryLogs":[["status":"false","tableName":"consultation","‌​type":"I","logId": id‌​s,"query":queryLogString]]] as [String : Any]
if let content = f.jsonString {
print(content)
}
}
Output:
{"queryLogs":[{"status":"false","query":"{\"contents\":{\"updated\":\"\",\"id\":1488199579,\"created\":\"\",\"patient_count\":60,\"isactive\":\"1\",\"status_id\":0,\"starttime\":\"\",\"queue_status_id\":0,\"date_consult\":\"\"},\"conditions\":\"{}\"}","tableName":"consultation","‌​type":"I","logId":{"id":"261489537666","doctorId":"100"}}]}
once try like,
let data = try? JSONSerialization.data(withJSONObject: dic, options: JSONSerialization.WritingOptions(rawValue: 0))
if let content = String(data: data!, encoding:
String.Encoding.utf8) {
print(content)
}

Json Tableview Swift

this post follows an old post where some people helped me for a similar problem.
I currently developing an app which list user object by making an request to a webservice, which send a response in JSON in this format :
{
"objects": [
{
"id": "28",
"title": "test",
"price": "56 €",
"description": "kiki",
"addedDate": "11-07-2015",
"user_id": "1",
"user_name": "CANOVAS",
"user_zipCode": "69330",
"category_id": "1",
"category_label": "VEHICULES",
"subcategory_id": "1",
"subcategory_label": "Voitures",
"picture": "",
"bdd": {},
"picture_url": "http://jdl-barreme-orange.dyndns.org/WEBSERVICE/pictures/test.JPG"
},
{
"id": "27",
"title": "ferrari",
"price": "55 €",
"description": "rouge jantes",
"addedDate": "11-07-2015",
"user_id": "1",
"user_name": "CANOVAS",
"user_zipCode": "69330",
"category_id": "1",
"category_label": "VEHICULES",
"subcategory_id": "1",
"subcategory_label": "Voitures",
"picture": "",
"bdd": {},
"picture_url": "http://jdl-barreme-orange.dyndns.org/WEBSERVICE/pictures/ferrari.JPG"
}
}
I search a method to retrieve for each dictionary the value title and price and put them in a tableView.
Code I used (tableviewcontroller) :
if let jsonArray = NSJSONSerialization.JSONObjectWithData(urlData!, options: nil, error: nil) as? [[String:AnyObject]] {
for dict in jsonArray {
if let title = dict["title"] as? String {
println(title)
}
}
}
But it doesn't work, I put a breakpoint, and Xcode stop to interpret here :
for dict in jsonArray
Thanks for your help.
This example JSON is not valid: it lacks a ] before the last }.
But I guess this is just a pasting typo and the JSON you're using is properly formatted, so your problem is that you need to first access the objects key of your dictionary.
This key holds a value of an array of dictionaries, so we're using it as a typecast:
if let json = NSJSONSerialization.JSONObjectWithData(urlData!, options: nil, error: nil) as? [String:AnyObject] {
if let objects = json["objects"] as? [[String:AnyObject]] {
for dict in objects {
if let title = dict["title"] as? String {
println(title)
}
}
}
}
First we cast the result of NSJSONSerialization.JSONObjectWithData as the dictionary: [String:AnyObject], then we access the value for the objects key, then we cast this value as an array of dictionaries: [[String:AnyObject]].
Remember, with JSON format, dictionaries are formatted with {} and arrays are formatted with [].
Your example is {key:[{},{}]} so it's a dictionary holding an array of dictionaries.
Update for Swift 2.0
if let json = try? NSJSONSerialization.JSONObjectWithData(urlData!, options: []) as? [String:AnyObject] {
if let objects = json?["objects"] as? [[String:AnyObject]] {
for dict in objects {
if let title = dict["title"] as? String {
print(title)
}
}
}
}
Try this :
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary
var DataFromJSon = jsonResult["objects"] as! NSArray
for one in DataFromJSon {
var title = one["title"] as! String
println(title)
}

Resources