How to Post Nested JSON by Swiftyjson and Alamofire

How to post nested json by SwiftyJson and Alamofire?

try this

func test()
{
var exampleParameters : [String : Any] = ["b" : "bv"]

exampleParameters["a"] = ["a1": "v1","a2": "v2"]

debugPrint(exampleParameters.description)

let devUrlPush = URL.init(string:"yourURL")

var request = URLRequest(url: devUrlPush!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

request.httpBody = try! JSONSerialization.data(withJSONObject: exampleParameters)

Alamofire.request(request).responseJSON { (response) in

if( response.result.isSuccess)
{

}else
{

}
}

let string = String(data: request.httpBody!, encoding: .utf8)
let jsonString = JSON(data: request.httpBody!)
debugPrint(jsonString.rawString(.utf8, options: .prettyPrinted))
debugPrint(string)
}

I hope this helps

How do I access a nested JSON value using Alamofire and SwiftyJSON?

In your JSON quotes is an array so if you want to access quote of the first object you should do it by accessing first object:

 func getAPI() {
Alamofire.request(.GET, "http://quotes.rest/qod.json", parameters: ["contents": "quotes"])
.responseJSON { response in
if let jsonValue = response.result.value {
let json = JSON(jsonValue)
if let quote = json["contents"]["quotes"][0]["quote"].string{
print(quote)
}
}
}
}

json post nested objects in swift using alamofire

after while i discovered my problem was with the Alamofire request i forgot to add the encoding parameter and the solution is

Alamofire.request("https://httpbin.org/post", parameters: parameters, encoding: URLEncoding.httpBody)

How to post nested json by objectMapper and Alamofire?

Based on the request structure, below is the simplified way to encode/decode ChartsReqModel object,

class  ChartsReqModel: NSObject, Mappable {
var TokenId:String?
var ObjSearch: ChartObjSearchReqModel?

required init?(map: Map) {}

func mapping(map: Map) {
self.TokenId <- map["TokenId"]
self.ObjSearch <- map["ObjSearch"]
}
}

Now when you have json from the response, you can decode ChartsReqModel object by passing that json as below,

let chartsObject = ChartsReqModel(JSON: jsonFromResponse)

And when you want to post the ChartsReqModel json, you can encode it as below

let paramsJson = chartsObject.toJSON()

Alamofire Post Request with nested JSON parameters

I believe the issue here is that Alamofire is trying to encode a parameter as json that is already a json object. Essentially, double-encoding causes the application to crash.

The solution I found was to decode the json parameter before performing the request using SwiftyJSON's .rawValue.

let parameters: Parameters = [
"firstName": "John",
"lastName": "Doe",
"address": address.rawValue
]

https://github.com/SwiftyJSON/SwiftyJSON#raw-object

Return a value in a nested JSON array, using Alamofire and Swift

You can use Decodable to get the desired result.

struct RootResponse: Decodable {

let destinationAddresses, originAddresses: [String]
let rows: [Rows]
let status: String
}

struct Rows: Decodable {

let elements: [Elements]
}

struct Elements: Decodable {

let distance, duration: Details
let status: String
}

struct Details: Decodable {
let text, value: String
}

This will be your model file and once you have added it then you can go back to your function and use it as:

func distanceMatrix(startLocation: String, endLocation: String) {
let myOrigin = startLocationTFText
let myDestination = destinationLocationTFText

let url = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=\(myOrigin)&destinations=\(myDestination)&key=API_Key"

let encodedUrl = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)

AF.request(encodedUrl!).responseJSON { response in
print(response.request as Any)
print(response.response as Any)
print(response.data as Any)
print(response.result as Any)

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase

guard let json = try? decoder.decode(RootResponse.self, from: response.data) else { print("Unable to parse JSON"); return }

print(json)
print(json.rows.first?.elements.first?.distance.value) // This is how you can get the value, but it will be better to safely unwrap them and I have also used first? to get the first object but this is an array and you can always use a for loop for further purpose
}

Parsing nested JSON with Alamofire 4

The API returns an array of dictionaries where each dictionary represents a Post of type [String: Any]:

Alamofire.request(_newsURL).responseJSON { response in
if let posts = response.result.value as? [[String: Any]] {
posts.forEach { post in
if let slug = post["slug"] as? String {
print("Slug: \(slug)")
}
if let title = post["title"] as? [String: String] {
print("Title: \(title["rendered"])")
}
if let categories = post["categories"] as? [Int] {
print("Categories: \(categories)")
}
// You can retrieve as many field as you like as above...
}
}
}

I strongly recommend you making use of an object mapping library such as ObjectMapper so you don't have to worry about type checking or casting at all.

Just create a model named Post:

import ObjectMapper

class Post: Mappable, CustomStringConvertible {

var title: String?
var slug: String?

var link: URL?
var content: String?

required init?(map: Map) {}

func mapping(map: Map) {
title <- map["title.rendered"]
slug <- map["slug"]

link <- (map["link"], URLTransform())
content <- map["content.rendered"]
}

var description: String {
return "Post <\(title ?? "No title")>"
}
}

so you can retrieve all posts as follows:

import AlamofireObjectMapper

Alamofire.request("http://www.wsvh.nl/wp-json/wp/v2/posts")
.responseArray { (response: DataResponse<[Post]>) in

// This will give you the array of Post objects.
print("Posts: \(response.result.value)")
}

I've created an example project for you. You can download and play around with it to have a better understanding about how mapping is performed.

AlamoFire 4.0 + SwiftyJSON Unwrapping deeply nested JSON

"pages" value is a dictionary so using [0] on it won't work, you need to use the key instead:

print("otherJSON: \(json["query"]["pages"]["1895477"]["extract"])")

Or if there are many items in pages and you want them all you can iterate through it like:

let pages = json["query"]["pages"]
for (_,page) in pages {
print(page["extract"])
}

How to use SwiftyJSON on nested JSON values

Try

var profileImage: String! = userDict["userImages"]["profile"][0]["filename"].string

var characterName: String! = userDict["characters"][0]["characterName"].string

and let us know what it gives.



Related Topics



Leave a reply



Submit