how to parse JSON array inside object in swift4 - ios

I'M using tableview to parsing JSON data. the parse data in tableview in successful parsed on my tableView but the problem is users click the tableview cell to pass to details ViewController.But the problem is i can't parse JSON in details ViewController in
here is my JSON looks
[
{
"id": "263",
"userId": "2692"
}
]
here is my code
guard let url = URL(string: URL API) else { return }
var request = URLRequest(url: url)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("Bearer \(AccessToken!)", forHTTPHeaderField: "Authorization")
request.httpMethod = "GET"
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
do {
let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [string: anyobject]
print(json)
label.text = json["id"] as? string
}catch {
}
}.resume()

Please try this codes
do {
if let json = try JSONSerialization.jsonObject(with: data!) as? [[String: String]] {
for data in json {
label.text = data["id"] as? String
}
}
} catch { print(error) }

Parse json in swift4 using Codable protocol.
declare your model like this:
struct Model: Codable {
let id: Double
let userId: Double
enum CodingKeys : String, CodingKey {
case id = "id"
case userId = "userId"
}
}
then, after getting data, use this:
do {
let arrayValue = try JSONDecoder().decode([Model], from: data)
}
catch {
}
Note that your json is array not dictionary!

Related

SWIFT - JSON error: The data couldn’t be read because it isn’t in the correct format

How to correct this error: JSON error: The data couldn’t be read because it isn’t in the correct format?
struct LanguageText: Decodable {
let id_language: Int
let language_text: String
}
func textLoad() {
let switchcase = "loginWords"
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
let postString = "switchcase=\(switchcase)"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
return // check for fundamental networking error
}
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
print(json)
} catch {
print("JSON error: \(error.localizedDescription)")
}
}.resume()
}
This is the JSON format:
[{"id_language":"15","language_text":"Female"},
{"id_language":"16","language_text":"Male"},
{"id_language":"17","language_text":"Other"},
{"id_language":"1000","language_text":"Hello there!"}]
Thanks!
You are trying to put id_language into a Int-Value, but in your JSON id_language is String.
Change id_language to String
struct LanguageText: Decodable {
let id_language: String
let language_text: String
}
Or you have to edit your JSON-File
[{"id_language":15,"language_text":"Female"},
{"id_language":16,"language_text":"Male"},
{"id_language":17,"language_text":"Other"},
{"id_language":1000,"language_text":"Hello there!"}]
For parsing JSON I can recommend this site
In your model you could do something like this:
struct LanguageText: Decodable {
let languageId: String
let languageText: String
enum CodingKeys: String, CodingKey {
case languageId = "id_language"
case languageText = "language_text"
}
}
In your do catch do the data parse:
do {
let result = try JSONDecoder().decode([LanguageText].self, from: data)
} catch {
print("JSON error: \(error.localizedDescription)")
}
Use this to get array from row data.
let dataArray = getArrayFromJsonString(rowData: data)
func getArrayFromJsonString(arrayString:String)-> [[String : Any]] {
do {
return try JSONSerialization.jsonObject(with:
arrayString.data(using:
String.Encoding.utf8, allowLossyConversion: false)!,
options:
JSONSerialization.ReadingOptions.allowFragments) as! [[String :
Any]]
} catch let error {
print("Error: \(error)")
return []
}
}

API URL to post json formatted data

How would I transfer code from textfields into json formatted data.
Below is the current code i have, but it doesn't seem to transfer the data within the textfields to json when the button is clicked. Is their any errors within this code?
#IBAction func submitButton(_ sender: Any) {
// parse in paramaters
let parameters = ["Name": nameTextField, "Email": emailTextField, "DOB": dateTextField] as [String : Any]
guard let url = URL(string: "https://prod-69.westeurope.logic.azure.com/workflows/d2ec580e6805459893e498d43f292462/triggers/manual/paths/invoke?api-version=2016-06-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=zn8yq-Xe3cOCDoRWTiLwDsUDXAwdGSNzxKL5OUHJPxo") else { return }
var request = URLRequest(url: url)
// let url session know that this is a post request
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
// convert paramaters to JSON
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else { return }
request.httpBody = httpBody
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let response = response {
print(response)
}
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
print(json)
} catch {
print(error)
}
}
}.resume()
}
Are nameTextField, emailTextField and dateTextField of type String or UITextField. Make sure you are passing the UITextField.text property and not the UITextField itself.
See below:
guard let name = nameTextField.text,
let email = emailTextField.text,
let dob = dateTextField.text else {
return
}
let parameters: [String: String] = ["name": name, "email": email, "dob": dob]

JSON response format is incorrect(Swift)

I am new to Swift and I am getting response from mysql through PHP script in JSON format. But my JSON is in correct format :
["Result": <__NSArrayI 0x60000005bc60>(
<__NSArray0 0x608000000610>(
)
,
{
name = "abc" ;
address = "abc address"
},
{
name = "xyz" ;
address = "xyz address"
}
)
]
my code for serialisation is :
let url = URL(string: "my url")
var request = URLRequest(url: url!)
request.httpMethod = "POST"
let body = "Id=\(Id)"
request.httpBody = body.data(using: .utf8)
// request.addValue("application/json", forHTTPHeaderField: "Content-type")
URLSession.shared.dataTask(with: request) { data, response, error in
if error == nil {
DispatchQueue.main.async(execute: {
do {
if let json = try! JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? Dictionary<String,Any>{
print(json)
Where am I going wrong?
POSTMAN output
{
"Result": [
{
name = "abc" ;
address = "abc address"
},
{
name = "xyz" ;
address = "xyz address"
}
]
}
Try it once.
let json = try! JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String:Any]
Swift 3.0
Try this code..
//declare parameter as a dictionary
let parameters = ["Id": Id"] as Dictionary<String, String>
//url
let url = URL(string: "http://test.com/api")!
//session object
let session = URLSession.shared
//URLRequest object using the url object
var request = URLRequest(url: url)
request.httpMethod = "POST"
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
} catch let error {
print(error.localizedDescription)
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
guard error == nil else {
return
}
guard let data = data else {
return
}
do {
//json object from data
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
print(json)
// handle json...
}
} catch let error {
print(error.localizedDescription)
}
})
task.resume()
Alamofire
Try this code using Alamofire..
let parameters = [
"name": "user1"]
let url = "https://myurl.com/api"
Alamofire.request(url, method:.post, parameters:parameters,encoding: JSONEncoding.default).responseJSON { response in
switch response.result {
case .success:
print(response)
case .failure(let error):
failure(0,"Error")
}
}
Make sure you get the response as json. Some times get string as response. If you get string then convert that json string to json object.
Check it is a valid json object
let valid = JSONSerialization.isValidJSONObject(jsonOBJ) // jsonOBJ is the response from server
print(valid) // if true then it is a valid json object

Why format is strange when JSON is parsed in Swift3?

I have a struggle in parsing JSON data using Oxford Dictionary API. I can retrieve JSON data and at this point, there is no problem. But the format is a bit strange. In the example of JSON data by OXford Document, it looks like;
"results": [
{
"id": "string",
"language": "string",
"lexicalEntries": [
{
"entries": [
{..........
Unlike the example above, the array in my JSON is not surrouned by [], but ()
Why is this happening??
Updated
I used Alamofire to produce it. The code is;
func getJSONData() {
let appId = ""
let appKey = ""
let language = "en"
let word = "play"
let word_id = word.lowercased()
let url = URL(string: "https://od-api.oxforddictionaries.com/api/v1/entries/\(language)/\(word_id)")!
var request = URLRequest(url: url)
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue(appId, forHTTPHeaderField: "app_id")
request.addValue(appKey, forHTTPHeaderField: "app_key")
Alamofire.request(request).responseJSON { response in
print("Request \(response.request)") // original URL request
print("Response \(response.response)") // HTTP URL response
print("Data \(response.data)") // server data
print("Result \(response.result)") // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
}
I followed all code in Oxford Dictionary Document, but the printed out JSON was far from the JSON in the document. So I tried to use Alamofire in the hope for it to work correctly, but the result was the same. https://developer.oxforddictionaries.com/documentation
Update2
Okay, I understood why this was an error. To people who might have the same problem, I post the answer for the problem I had.
enum JSONError: String, Error {
case NoData = "ERROR: no data"
case ConversionFailed = "ERROR: conversion from JSON failed"
}
func jsonParser() {
let appId = ""
let appKey = ""
let language = "en"
let word = "Ace"
let word_id = word.lowercased() //word id is case sensitive and lowercase is required
let url = URL(string: "https://od-api.oxforddictionaries.com:443/api/v1/entries/\(language)/\(word_id)")!
var request = URLRequest(url: url)
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue(appId, forHTTPHeaderField: "app_id")
request.addValue(appKey, forHTTPHeaderField: "app_key")
URLSession.shared.dataTask(with: request) { (data, response, error) in
do {
guard let data = data else {
throw JSONError.NoData
}
guard let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? NSDictionary else {
throw JSONError.ConversionFailed
}
if let stringJSON = String(data: data, encoding: String.Encoding.utf8) {
print(stringJSON)
}
print(json)
} catch let error as JSONError {
print(error.rawValue)
} catch let error as NSError {
print(error.debugDescription)
}
}.resume()
}
Strange printed JSON format This post helped me. This bugged me for a while. Thank you very much #EricAya

How to save JSON data from a POST Request into dictionary with Swifty Json?

I was able to print the json data in console which looks like this
{
"created_at" : "2016-07-21 20:46:53",
"name" : "PB Admin",
"id" : 1,
"updated_at" : "2016-07-21 12:46:53",
"lname" : "Admin",
"access_lvl" : 1,
"email" : "admin#admin.com",
"fname" : "PB"
}
, but could not save it into a dictionary.
The method for POST request
private func makeHTTPPostRequest(path: String, body: NSDictionary) {
let request = NSMutableURLRequest(URL: NSURL(string: path)!)
// Set the method to POST
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.HTTPMethod = "POST"
do {
// Set the POST body for the request
let jsonBody = try! NSJSONSerialization.dataWithJSONObject(body, options: [])
request.HTTPBody = jsonBody
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
let json:JSON = JSON(data: data!)
print(json)//print on console
//i need to get the json data from here, but for some reason it would skip
//this method
self.parseJSON(json)
})
task.resume()
} catch {
// Create your personal error
//onCompletion(nil, nil)
}
}
This method should save the json data into a dictionary
private func parseJSON(json: JSON) {
for(_, object) in json {
let createdAt = object["created_at"].stringValue
let name = object["name"].stringValue
let id = object["id"].stringValue
let updatedAt = object["updated_at"].stringValue
let lName = object["lname"].stringValue
let accessLvl = object["access_lvl"].stringValue
let email = object["email"].stringValue
let fname = object["fname"].stringValue
let obj = ["createdAt":createdAt, "name":name, "id":id, "updatedAt":updatedAt, "lName":lName, "accessLvl":accessLvl, "email":email, "fname":fname ]
objects.append(obj)//wherein objects is a string dictionary
}
}
Whenever I debug the code, objects dictionary is always null even if the whole processed has finished.
You can convert your JSON data to NSData so you can easly get yor data from NSData rather than JSON.
public class func jsonToNSData(json: AnyObject) -> NSData?{
return NSJSONSerialization.dataWithJSONObject(json, options: .allZeros, error: nil)
}
Then you can create a function that returns NSDictionary like this:
func parseJSON(data: NSData) -> NSDictionary{
var dic: NSDictionary!
do {
boardsDictionary = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
} catch let error as NSError {
print(error.localizedDescription)
print("Error could not parse JSON data, it's null maybe?!!")
}
//'\(jsonStr)'
return dic
}
Last One: Create your dictionary
let dic = parseJSON(jsonToNSData(YourJsonData)) as! NSDictionary
Hope it helps.
let jsonDictionary = try! NSJSONSerialization.JSONObjectWithData(data!,
options: NSJSONReadingOptions.MutableContainers) as! NSDictionary

Resources