Unable to convert this JSON to a string - ios

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

Related

Send JSON with array of objects as parameter in Alamofire with swift

I am very new with Swift and Alamofire, what I want to accomplish is to send a data structure, like this:
{
"name" : "Test name",
"intention" : "Purpose of practice test",
"id_frequency" : "1",
"member": [
{
"id_member" : "1",
"email" : "member1#gmail.com",
"id_member_type" : 1
},
{
"id_member" : "4",
"email" : "member2#gmail.com",
"id_member_type" : 3
},
{
"id_member" : "7",
"email" : "member3#gmail.com",
"id_member_type" : 3
},
{
"id_member" : "5",
"email" : "member4#gmail.com",
"id_member_type" : 3
},
{
"id_member" : "6",
"email" : "member5#gmail.com",
"id_member_type" : 3
}
]
}
The way I am proceeding to structure the desired json, is as follows:
var membersArray = [AnyObject]()
for i in 0..<members.count {
let json: [String: Any] = [
"id_member": members[i].idMember!,
"email": members[i].email!,
"id_member_type": "\(Int(members[i].idMemberType)!)",
]
membersArray.append(json as AnyObject)
}
let jsonMembers = JSON(membersArray)
let jsonObject: [String: Any] = [
"member" : jsonMembers,
"name": name!,
"intention": intention!,
"id_frequency": frequency!
]
let jsonUpdate = JSON(jsonObject)
With this structured json, lines above (jsonUpdate). I proceed to execute the webService.
WevServices.createRequest(requestInfo: jsonUpdate) { (result) in
print(result)
}
My webservice method, looks like this:
static func createRequest(requestInfo: JSON, completion: #escaping (_ result: String) -> Void){
let url = URL(string: "http://ws.someURL.com/CreateRequest")
let parameters: [String : Any] = ["name" : "\(requestInfo["name"])", "intention" : "\(requestInfo["intention"])", "id_frequency" : "\(requestInfo["id_frequency"])", "member": requestInfo["member"]]
Alamofire.request(url!, method: .post, parameters: parameters, encoding: URLEncoding.httpBody).responseString { response in
print(response)
}
}
I'm get an error from the server that the send data would not be correct.
Note: My application use Lumen as backend.
The best way for doing what you need is :
func JSONToString(json: [String : String]) -> String?{
do {
let mdata = try JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions.prettyPrinted) // json to the data
let convertedString = String(data: mdata, encoding: String.Encoding.utf8) // the data will be converted to the string
print("the converted json to string is : \(convertedString!)") // <-- here is ur string
return convertedString!
} catch let myJSONError {
print(myJSONError)
}
return ""
}
and for alamofire request do this :
static func createRequest(requestInfo: [String :String], completion: #escaping (_ result: String) -> Void){
let url = URL(string: "http://ws.someURL.com/CreateRequest")
let parameters: [String : Any] = ["request" : JSONToString(json : requestInfo)!]
Alamofire.request(url!, method: .post, parameters: parameters, encoding: URLEncoding.httpBody).responseString { response in
print(response)
}

Unable to convert json string to json object

let dictionaryToJsonObject: [String: Any]
let Dictionary: [String: Any] = ["FirstName": "John", "Email": "Jo#sm.com", "Password": "john#123", "LastName": "Smith", "Organization": ["Type": 5, "Name": "IT"]]
do {
let jsonData = try JSONSerialization.data(withJSONObject: Dictionary as Any, options: .prettyPrinted)
let jsonText = String(data: jsonData,
encoding: .ascii)
print("JSON string = \(jsonText!)")
if JSONSerialization.isValidJSONObject(jsonText!) {
print("Valid")
} else {
print("Not Valid")
}
}catch {
print(error.localizedDescription)
}
Output Will be : -
JSON string = {
"FirstName" : "John",
"Email" : "Jo#sm.com",
"Password" : "john#123",
"LastName" : "Smith",
"Organization" : {
"Type" : 5,
"Name" : "IT"
}
}
expected Result :
{
FirstName:"John",
Email:"Jo#sm.com",
Password:"john#123",
LastName:"Smith",
Organization:{
Type:5,
Name:"IT"
}
}
If you want to get it in json object form then your code should be like,
let dictionaryToJsonObject: [String: Any]
let Dictionary: [String: Any] = ["FirstName": "John", "Email": "Jo#sm.com", "Password": "john#123", "LastName": "Smith", "Organization": ["Type": 5, "Name": "IT"]]
do {
let jsonData = try JSONSerialization.data(withJSONObject: Dictionary as Any, options: .prettyPrinted)
let jsonObject = try JSONSerialization.jsonObject(with: jsonData, options: .init(rawValue: 0))
print("JSON string = \(jsonObject)")
if JSONSerialization.isValidJSONObject(jsonObject) {
print("Valid")
} else {
print("Not Valid")
}
}catch {
print(error.localizedDescription)
}
and your output will be,
JSON string = {
Email = "Jo#sm.com";
FirstName = John;
LastName = Smith;
Organization = {
Name = IT;
Type = 5;
};
Password = "john#123";
}
Valid
Ultimately it is your declared dictionary itself I think!

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
}

Convert array of dictionaries to JSON Format

my api expects to receive JSON data in below form
{
"user_contacts" : [
{
"friend_list" : "+928885555512",
"user_id" : "1"
},
{
"friend_list" : "+925555648583",
"user_id" : "1"
},
{
"friend_list" : "+925555228243",
"user_id" : "1"
}
]
}
i have created this data through array of dictionaries and its working fine and it is stores in Data type Variable. As alamofire requires [String: Any] type of parameter so i have to convert that data into desired format so i tried this:
let my_dict = try JSONSerialization.jsonObject(with: jsonData!, options: []) as! [String: Any]
but when print this my_dict before call alamofire. it seems that it is not a correct json see below... with something like that: __NSArrayI 0x618000271dc0>
["user_contacts": <__NSArrayI 0x618000271dc0>(
{
"friend_list" = "+928885555512";
"user_id" = "1";
},
{
"friend_list" = "+925555228243";
"user_id" = "1";
},
{
"friend_list" = "+925554787672";
"user_id" = "1";
}
)
]
So how can i make this correct json form?
what i am doing wrong?
Updated:
let updated_User_No :[String:Any]=["friend_list": self.new_convert_telephone_no,"user_id": user_no];
user_outer_arrary.append(updated_User_No);
user_inner_array=["user_contacts": user_outer_arrary]
it Should be look like this:
{
"user_contacts" : [
{
"friend_list" : "+928885555512",
"user_id" : "1"
},
{
"friend_list" : "+925555648583",
"user_id" : "1"
}
]
}
Perform JSONSerialization as below:
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? Dictionary<AnyHashable, Any>
Try this :
Create Structure
let users = ["" : ["user_contacts": [["friend_list":"user_id"],["friend_list3":"user_id3"]]]]
Create Json Object
let json = try JSONSerialization.jsonObject(with: data!, options:.prettyPrinted) as? [String : AnyObject]

Loop through JSON response from Alamofire

I am using xcode 7.2 and swift 2.1.1. using Alamofire for server communication. I have a tableview that display's dynamic data.Data includes username , useremail , profilePicture etc. I Tried to implement this code from stackoverflow. But I am getting a warning message says Cast from 'JSON' to unrelated type '[Dictionary]' always fails My json response is
{
"JsonRequestBehavior" : 1,
"MaxJsonLength" : null,
"ContentType" : null,
"Data" : {
"_id" : "5658444778a7531f4c79c23d",
"Photo" : "",
"AllowSharing" : "YES",
"MemberCount" : 5,
"Users" : [
{
"_id" : "5658443478a7531f4c79c23c",
"Photo" : "",
"MembershipDate" : "0001-01-01T00:00:00",
"MiddleName" : null,
"FirstName" : "Gohan",
"LastName" : null,
"Email" : "gohan#gmail.com"
},
{
"_id" : "566ea5f1dfead62350cf0fad",
"Photo" : "",
"MembershipDate" : "0001-01-01T00:00:00",
"MiddleName" : null,
"FirstName" : null,
"LastName" : null,
"Email" : "sachin#gmail.com"
}
],
"MembershipDate" : "2015-12-14T12:03:12.819Z",
"CreatedBy" : "5658443478a7531f4c79c23c"
},
"ContentEncoding" : null,
"RecursionLimit" : null
}
How can I loop through Users in JSON response ?
EDIT as per JohnyKutty's answer I tried the same code in my Project. The code for the same is
Alamofire.request(.GET,App.AppHomeURL() + "Load_Group", parameters: ["groupid":"\(groupId)"]).responseJSON
{
response in
print("\(response.data)")
switch response.result
{
case .Success(let _data):
let jsonData = JSON(_data)
print("Admin Response : \(jsonData)")
do
{
let json = try NSJSONSerialization.JSONObjectWithData(_data as! NSData, options: .AllowFragments) as! NSDictionary
if let DataObject = json["Data"] as? NSDictionary
{
if let users = DataObject["Users"] as? [NSDictionary]
{
for user in users
{
print("User id : \(user["_id"])")
}
}
}
}
catch let error as NSError
{
print(error.localizedDescription)
}
in this line let json = try NSJSONSerialization.JSONObjectWithData(_data as! NSData, options: .AllowFragments) as! NSDictionary
At first I used "_data" and then Xcode suggested a change and it changed from _data to _data as! NSData.
Your son structure is like following
JSON(Dictionary) -> Data(Dictionary) -> Users(Array of Dictionaries). So first you should pick the Users array from raw json then iterate through it.
Since alamofire is already serializing your response, No need to use JSONSerializer again, I am updating my answer.
UPDATE
Try this code inside the case
if let DataObject = _data["Data"] as? NSDictionary {
if let Users = DataObject["Users"] as? [NSDictionary] {
for user in Users {
print(user["_id"],user["MembershipDate"],user["FirstName"],user["Email"], separator: " ", terminator: "\n")
}
}
}
Full code:
Alamofire.request(.GET,App.AppHomeURL() + "Load_Group", parameters: ["groupid":"\(groupId)"]) .responseJSON { response in
switch response.result {
case .Success(let _data):
print(_data)
if let DataObject = _data["Data"] as? NSDictionary {
if let Users = DataObject["Users"] as? [NSDictionary] {
for user in Users {
print(user["_id"],user["MembershipDate"],user["FirstName"],user["Email"], separator: " ", terminator: "\n")
}
}
}
default:
break;
}
}

Resources