i am trying to parse JSON data from web service into my Swift
JSON Output on my web browser:
[{"code":0,"message":"Check Username and Password....","userid":""}]
Swift Code:
Alamofire.request(URL_USER_LOGIN, method: .post, parameters: parameters).responseJSON
{
response in
//printing response
print(response)
if let userJSON = response.result.value
{
let userdata:Dictionary = userJSON as! Dictionary<String, Any>
let message:Dictionary = userdata["message"] as! Dictionary<String, Any>
print(message)
}
I want to use message element from the JSON for my code. However i get the following output and error:
(
{
code = 1;
message = "Login Successfull";
userid = 236;
}
)
Could not cast value of type '__NSSingleObjectArrayI' (0x10fd94b98) to 'NSDictionary' (0x10fd958b8).
2018-11-03 20:15:10.762929+0530 testDisplayTable[44610:2871941]
Could not cast value of type '__NSSingleObjectArrayI' (0x10fd94b98) to 'NSDictionary' (0x10fd958b8).
How do I successfully get the value of message and print? Can someone please show me the correct code for my case. Thanks in advance!
It's an array not dictionary
if let userdata = userJSON as? [[String:Any]] {
if let message = userdata[0]["message"] as? String {
print(message)
}
}
Related
I would like to assign a value from JSON to a variable, the issue is Swift thinks I am passing an entire array and not just the JSON value of code to the variable.
I have the following structure and JSON decode function:
private func JSONFunction() {
guard let url = URL(string: "https://example.com/example/example"),
let nameValue = stringValue.addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed)
else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = "name=\(nameValue)".data(using: .utf8)
URLSession.shared.dataTask(with: request) { data, _, error in
guard let data = data else { return }
do {
let myData = try JSONDecoder().decode(codeStruct.self, from:data)
DispatchQueue.main.async {
codeNum = myData.code
print(codeNum)
}
}
catch {
print(error)
}
}.resume()
}
The following is the structure for decoding the JSON:
struct codeStruct: Codable {
let code: String
let line: String
let person: String
let maker: String
}
Error received:
typeMismatch(Swift.Dictionary,
Swift.DecodingError.Context(codingPath: [], debugDescription:
"Expected to decode Dictionary but found an array
instead.", underlyingError: nil))
Without looking at the json, if I were to guess, I would say that your incoming JSON is actually an array of codeStruct objects, for which you should change your line to
let myData = try JSONDecoder().decode([codeStruct].self, from:data)
I'm trying to use Alamofire to get a response from web-service.
The service is returning a string in JSON format but I'm getting the error: 'Could not cast value of type NSCFString to NSDictionary'
My code is:
func getSoFromMo() {
let apiUrl: String = "http://xxxxxxxxxxxxxxx"
Alamofire.request(apiUrl)
.responseJSON{ response in
print(response)
if let resultJSON = response.result.value {
let resultObj: Dictionary = resultJSON as! Dictionary<String, Any> <==== Breaks on this line
self.soNum = resultObj["soNumber"] as! String
self.lblValidate.text = "\(self.soNum)"
} else {
self.soNum = "not found!"
}
}
When I print the response I get - SUCCESS: {"SoNumber": "SO-1234567"}
When I test the URL using Postman the result is: "{\"soNumber\": \"SO-1234567\"}" including all the quotes, so the format doesn't quite look correct to me, perhaps the leading and trailing double quotes are throwing it off?
The error is clear. The result is a JSON string rather than a deserialized dictionary.
You have to add a line to deserialize the string
func getSoFromMo() {
let apiUrl: String = "http://xxxxxxxxxxxxxxx"
Alamofire.request(apiUrl)
.responseJSON { response in
print(response)
do {
if let data = response.data,
let resultObj = try JSONSerialization.jsonObject(with: data) as? [String:Any] {
self.soNum = resultObj["soNumber"] as! String
self.lblValidate.text = self.soNum // no String Interpolation, soNum IS a string
} else {
self.soNum = "not found!"
}
} catch {
print(error)
}
}
}
I am using two textfields to pass login information to the PHP web service using Alamofire in the following way.
#IBAction func LoginButton(_ sender: Any) {
//getting the username and password
let parameters: Parameters=[
"Name":TextFieldUserName.text!,
"Pass":TextFieldPassword.text!
]
Alamofire.request(URL_USER_LOGIN, method: .post, parameters: parameters).responseJSON
{
response in
//printing response
print(response)
The following Json data is received on login.
[{"code":0,"message":"Check Username and Password....","userid":""}]
I want to use either "code" value (0 for false and 1 for true) or "message" value as String to put into an if - else statement for further steps. If Alamofire is not the best way to go about this, can someone please show another way. Thanks in advance for the help.
Do you need to deserialize the response from the server?
The easiest option is parsing response value as NSDictionary
if let JSON = response.result.value as? NSDictionary {
let code = JSON.value(forKey: "code") as? Int
let message = JSON.value(forKey: "message") as? String
}
You can also use the Codable protocol and the JSONDecoder to decode this response into your structure.
For example, declare struct:
struct LoginResponse: Codable {
var code: Int
var message: String
}
and decode response using JSONDecoder
let jsonDecoder = JSONDecoder()
let loginResponse = try? jsonDecoder.decode(LoginResponse.self, from: response.data)
How to parse below json response in swift. I want to get the value of "code"
jsonResponse : {
messages = (
{
code = "MM_777";
message = "Password wrong";
}
);
}
Done it!
if let messages = fromJsonResponse.first {
let value = messages.value as! Array<AnyObject>
let dict = value.first as? [String: Any]
print(dict!["code"] ?? "lax")
}
I am trying to parse the response from Alamofire but I can't figure out how to do it.
This is the JSON Response I get (I want to parse out "result") how is this done?
JSON: {
result = 887957;
status = 0;
}
Swift 3
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
You just need to specify the type of response is Dictionary and then use subscript with dictionary to get value of result.
if let dictionary = response.result.value as? [String: Int] {
let result = dictionary["result"] ?? 0
print(result)
}
if let JSON = response.result.value as? [String : Any] {
let result = JSON["result"] as? Int
let status = JSON["status"] as? Int
print("Result \(result) Status \(status)")
}
As per latest Almofire Lib and Swift 3.0 with proper validation:
case .success(_):
if ((response.result.value) != nil) {
var responseData = JSON(response.result.value!)
//Userdefaults helps to store session data locally just like sharedpreference in android
if (response.response ? .statusCode == 200) {
let result: Int = responseData["result"].int!
let status: Int = responseData["status"].int!
}
}
case .failure(_):
print(response.result)
}