如何在文本字段中获取GET方法的JSON数据。我的Json数据如下,
SUCCESS: {"code":200,
"shop_detail":{"name":"dad","address":"556666","city":"cSC","area":"scsc","street":"vddva","building":"jhkj","description":null}
"shop_types":
[{"id":7,"name":"IT\/SOFTWARE","merchant_type":"office",}]}
我的带有标题和URL的代码是
func getProfileAPI() {
let headers: HTTPHeaders = [
"Authorisation": AuthService.instance.tokenId ?? "",
"Content-Type": "application/json",
"Accept": "application/json"
]
print(headers)
let scriptUrl = "http://haitch.igenuz.com/api/merchant/profile"
if let url = URL(string: scriptUrl) {
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = HTTPMethod.get.rawValue
urlRequest.addValue(AuthService.instance.tokenId ?? "", forHTTPHeaderField: "Authorization")
urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
urlRequest.addValue("application/json", forHTTPHeaderField: "Accept")
Alamofire.request(urlRequest)
.responseString { response in
debugPrint(response)
print(response)
if let result = response.result.value // getting the json value from the server
{
}
}
在打印响应后,如果我具有诸如name.text,address.text之类的文本字段,那么我将获取打印的JSON数据的值。我想通过JSON响应显示值。如果我尝试下面的代码,它将在Dictionary中失败。
if let data = data {
print(data)
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
let jsonData:NSDictionary = (data as? NSDictionary)!
print(jsonData)
}}
答案 0 :(得分:0)
尝试一下
struct Root: Codable {
let code: Int
let shopDetail: ShopDetail
let shopTypes: [ShopType]
}
struct ShopDetail: Codable {
let name, address, area, street, building, city: String
}
struct ShopType: Codable {
let name, merchantType: String
}
并致电
func getProfileAPI() {
let headers: HTTPHeaders = [
"Authorisation": AuthService.instance.tokenId ?? "",
"Content-Type": "application/json",
"Accept": "application/json"
]
print(headers)
let scriptUrl = "http://haitch.igenuz.com/api/merchant/profile"
if let url = URL(string: scriptUrl) {
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = HTTPMethod.get.rawValue
urlRequest.addValue(AuthService.instance.tokenId ?? "", forHTTPHeaderField: "Authorization")
urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
urlRequest.addValue("application/json", forHTTPHeaderField: "Accept")
Alamofire.request(urlRequest).response { response in
guard
let data = response.data,
let json = String(data: data, encoding: .utf8)
else { return }
print("json:", json)
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let root = try decoder.decode(Root.self, from: data)
print(root)
self.t1.text! = root.shopDetail.name
// self.t3.text! = root.shopDetail.description
print(root.shopDetail.name)
print(root.shopDetail.address)
for shop in root.shopTypes {
self.merchant_Type.text! = shop.merchantType
self.t2.text! = shop.name
print(shop.name)
print(shop.merchantType)
}
} catch {
print(error)
}
}}}