Alamofire POST JSON ARRAY - json

Alamofire - SWIFT JSON ARRAY
I want to Pass JSON ARRAY like this -
[
{
"OrgId": 1001,
"ClassworkId": 999800580,
}, {
"OrgId": 1001,
"ClassworkId": 0,
}
]
I am Using this Method - I want to solve parameter - [String : AnyObject] -> Array
func delateClasswork (parameters: [String: AnyObject],completion: (success : Bool) -> Void) {
request(.POST, "strURL", parameters: parameters, encoding:.JSON).responseJSON {
response in switch response.result {
case .Success(let JSON):
if((JSON.valueForKey("StatusId")) as! NSNumber == 1){
completion(success: true)
break
}else{
completion(success: true)
break
}
case .Failure(let error):
completion(success : false)
break
}
}
}

Assign the whole data to one parameter data, this will maintain the Type to [String:AnyObject].
let parameters:[String:AnyObject] = [
"data" : [
[
"OrgId": 1001,
"ClassworkId": 999800580,
],
[
"OrgId": 1001,
"ClassworkId": 0,
]
]
]
At the server end you have to parse the data using data key.

Related

Apollo graphQL: Error decoding Array while using custom scalars in iOS swift

I have schema as show below. Here question_r is an array of dictionaries received as Json. I am facing issue converting it. Is there any way i can successfully decode it?
"questionR": [
{
"identifier": "123",
"skills": {
"primary_skill": "vocabulary",
"secondary_skill": "reading",
}
}
]
This is the schema
{
"name": "question_r",
"description": "",
"args": [],
"type": {
"kind": "SCALAR",
"name": "Json",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
}
}
My script looks like this:
SCRIPT_PATH="${PODS_ROOT}/Apollo/scripts"
cd "${SRCROOT}/${TARGET_NAME}"
"${SCRIPT_PATH}"/run-bundled-codegen.sh codegen:generate --target=swift --includes=./**/*.graphql --passthroughCustomScalars --localSchemaFile="schema.json" API.swift
This is the typealias where i am defining Json. It can ve dictionary or array of dictionary
public typealias Json = [String:Any?]
extension Dictionary: JSONDecodable {
public init(jsonValue value: JSONValue) throws {
guard let dictionary = value as? Dictionary else {
throw JSONDecodingError.couldNotConvert(value: value, to: Dictionary.self)
}
self = dictionary
}
}
extension Array: JSONDecodable{
public init(jsonValue value: JSONValue) throws {
guard let array = value as? Array else {throw JSONDecodingError.couldNotConvert(value: value, to: Array.self)}
self = array
}
}
Any workaround for this? Am i missing something here?
I got it working by assuming Json to be an array and converting a dictionary to array.
public typealias Json = [[String:Any?]]
extension Json: JSONDecodable{
public init(jsonValue value: JSONValue) throws{
guard let array = value as? Array else {
guard let dict = value as? Dictionary<String, Any> else { throw JSONDecodingError.couldNotConvert(value: value, to: Dictionary<String, Any>.self)
}
self = .init(arrayLiteral: dict)
return
}
self = array
}
}
This works for me.

JSON Array Swift send using Alamofire

I am trying to send an array of JSON object which I need to update object on my server. I need the array for params request.
This is my construction of array I need in order to update server object value:
[{
"propName":"number", "value":numberValue
}]
Here is what I am trying to make in Swift :
let params = [
{ "propName":"number", "value":numberValue },
{ "propName":"address", "value":addressValue },
{ "propName":"notes", "value":notesValue },
{ "propName":"latitude", "value":latitudeValue },
{ "propName":"longitude", "value":longitudeValue}
] as [String: Any]
let updateParkingSpotRequest = AF.request(URLs.MarkParkingSpotAsAvail(parkingSpotId: parkingSpotId), method: .patch, parameters: params, encoding: JSONEncoding.prettyPrinted, headers: nil, interceptor: nil, requestModifier: nil)
But it doesn't work since it cannot convert this form of data, XCode says: "Cannot convert value of type '[() -> String]' to type '[String : Any]' ". How can I get that format of Data which server needs?
You need to write the initializer like this:
let params = [
[ "propName": "number", "value": numberValue ],
[ "propName": "address", "value": addressValue ],
[ "propName": "notes", "value": notesValue ],
[ "propName": "latitude", "value": latitudeValue ],
[ "propName": "longitude", "value": longitudeValue ]
] as [[String: Any]]
i.e. params is an Array of Dictionaries of String to Any.
The parameters parameter is a type of [String: Any] in Alamofire. So you need to create a parameter dictionary.
So assume that you have a list of Data models, you can create the params like below;
struct Data {
var propName: String
var value: Any
}
let values: [Data] = [
Data(propName: "number", value: numberValue),
Data(propName: "address", value: addressValue),
Data(propName: "notes", value: notesValue),
Data(propName: "latitude", value: latitudeValue),
Data(propName: "longitude", value: longitudeValue)
]
let params: [String: Any] = Dictionary(uniqueKeysWithValues: values.map{ ($0.propName, $0.value) })

Casting dictionary of sets to JSON Object

I'm trying to build request body like this form:
{
"user": {
"id": 1,
"id": 2,
"id": 4
}
}
My first idea was built json from string and cast it to dictionary String and Any, but this solution have a issue. Some "id" are missing on casting by JSONSerialization step.
I tried to use:
var dictionary: [String : Any] = ["name" : "John"]()
var selectedIDs = Set<NSDictionary>()
// Adding values to selectedIDs set
let userIDDict = ["id" : id] as NSDictionary
selectedIDs.insert(userIDDict)
dictionary.updateValue(selectedIDs, forKey: "user")
But it cannot be cast by JSONSerialization (Invalid type in JSON write).
How can i resolve problem, which i'm facing?
Creating this request is not a problem; it's just not proper JSON, so you shouldn't try to use JSONSerialization. It's just a string, and so you can create that string:
let idKeyValues = ids.map { "\"id\": \($0)" }.joined(separator: ",\n ")
let request = """
{
"user": {
\(idKeyValues)
}
}
"""
===>
{
"user": {
"id": 1,
"id": 2,
"id": 4
}
}
The proper way to express this in JSON would be:
{
"user": {
"ids": [1, 2, 4]
}
}
With that, a Codable implementation should be very straightforward.

Swift parsing JSON, nested array

{
"def": [
{
"sseq": [
[
[
"sense",
{
"sn": "1",
"dt": [
[
"text",
"{bc}a set of the equipment used in a particular activity {bc}{sx|gear||} "
],
[
"vis",
[
{
"t": "fishing {wi}tackle{/wi}"
}
]
]
]
}
]
]
]
}
]
}
jsonFormat
I am having trouble parsing this JSON, with the nested arrays. I am trying to get to the definition under "text" in "dt". The current output is something like this, while I am just trying to get to the definition:
["text", "{bc}to emit puffs (as of breath or steam)"]
["text", "{bc}to make empty threats {bc}{sx|bluster||}"]
["text", "{bc}to react or behave indignantly"]
for result in jsonArray {
if let def = result["def"] as? JsonArray {
for defItem in def {
//print(defItem)
if let sseq = defItem["sseq"] as? [Any] {
for _1 in sseq {
if let _1arr = _1 as? [Any] {
for _2 in _1arr {
if let _2arr = _2 as? [Any] {
for _3 in _2arr {
if let res = _3 as? JsonDict {
if let definitions = res["dt"] as? [[String]] {
print(definitions[0])
}
As #Robert pointed out, this JSON is in a bad place. As a fun thought exercise here's what you can do.
Formatted json:
{
"def":[
{
"sseq":[
[
[
"sense",
{
"sn":"1",
"dt":[
[
"text",
"{bc}a set of the equipment used in a particular activity {bc}{sx|gear||} "
],
[
"vis",
[
{
"t":"fishing {wi}tackle{/wi}"
}
]
]
]
}
]
]
]
}
]
}
Meet Swift Codable:
let woah = try? newJSONDecoder().decode(Woah.self, from: jsonData)
// MARK: - Woah
struct Woah {
let def: [Def]
}
// MARK: - Def
struct Def {
let sseq: [[[SseqElement]]]
}
enum SseqElement {
case sseqClass(SseqClass)
case string(String)
}
// MARK: - SseqClass
struct SseqClass {
let sn: String
let dt: [[DtUnion]]
}
enum DtUnion {
case dtClassArray([DtClass])
case string(String)
}
// MARK: - DtClass
struct DtClass {
let t: String
}

Adding [[String:AnyObject]] as parameter on Alamofire call (Swift 2)

I have this JSON (this is a simplified version):
{
"from":0,
"location": [{
"city":"Barcelona"
}]
}
And i'm trying to do an Alamofire request with this JSON on parameters. So I have typed something like this:
let parameter = [
"from":0,
"location": [
["city": "Barcelona"]
]
]
But it seems Alamofire doesn't accept the parse from [{ }] to [[]] on parameters. I have read that one way to solve this is using a MutableURLRequest but i don't find any clear example.
Alamofire.request(.GET, "http://myurl", parameters: (params as! [String : AnyObject]), headers: nil).responseCollection { (response: Response<[Group], NSError>) in
switch response.result {
case .Success(let groups):
print("Success")
case .Failure(_):
print("Failure")
}
}
This code above works and I get a result from this Alamofire Request but ignores this:
"location": [ ["city": "Barcelona"]]
Could someone can help with that? Thank you so much.