I am sending an array to an API endpoint, but the array is not going throuhg correctly. Here is what I have:
User:
name
email
So in my case I have a swift array of two users:
po userArray
▿ 2 elements
▿ [0] : <User: 0x7fa3ab597fd0>
▿ [1] : <User: 0x7fa3ab597bb0>
The JSON that the server expects is:
{users: [ {name:'john', email:'john#example.com'}, {name:'tom', email: 'tom#example.com' }]
What I'm sending:
'users' : userArray
But there seems to be a serialization issue. What the server is getting from me is this:
'users': ['MyApp.User', 'MyApp.User']
I'm using AlamoFire to send my PUT request.
Do I need to do convert the array to JSON before sending it out? I'm new to Swift and any help is appreciated.
You need to convert your User object into dictionary. Than you should add as value not array of users, but array of dictionaries.
You need to override description property for the custom class User
class User : NSObject
{
var name : String
var age : String
override var description : String
{
get{
return ["name" : self.name, "age" : self.age].description
}
}
}
Related
I've been trying to retrieve the value of code for a while now. This is the json I'm getting back from the server:
{
"message": "The given data was invalid.",
"errors": {
"code": [
"The code has already been taken."
]
}
}
How do I get the value of "code" with swiftyJson?
I've already tried this but I don't think it's correct.
let list: Dictionary<String, JSON> = json["errors"].dictionaryValue
var retunValue = list.values.first
You can access the first element of the "code" array like this:
json["errors"]["code"].array?.first?.string
This will give you nil if code were an empty array, or the JSON isn't the expected structure.
Since "code" is an array, it might contain more than 1 string, so you might want a [String] instead:
json["errors"]["code"].array?.compactMap { $0.string } ?? []
This will give you an empty array if the JSON is not the expected structure.
Hello I have a json the returns me some parameters as variables.
It has Parameter1, Parameter2, Parameter3 etc..
I don't know how many parameters will it give me. It's not a list it's just different variables in the json.
Which is the best way to map a json like that? I use Object Mapper
For Example:
First Time the json is
{
"MyObject": {
"Parameter1": "p1",
"Parameter2": "p2",
"Parameter3": "p3",
"Parameter4": "p4"
}
}
And a second time the json is
{
"MyObject": {
"Parameter1": "p1",
"Parameter2": "p2",
"Parameter3": "p3"
}
}
You can try this.
let keyvalue = parentDict.value(forKey: "MyObject") as! NSDictionary
var lastValue = Keyvalue.allValues
var lastKey = Keyvalue.allKeys
for Keyname in Keyvalue.allKeys
{
print("Keyname %#",Keyname)
print("Value %#",Keyvalue.value(forKey:Keyname))
}
the first step to parse any JSON to make it reusable is to create your Model class or struct accordingly.
Create a class called MyObject as same as your json dictionary
Create a let/var property parameters: [String]?. It's optional as API isn't reliable and maybe wont send anything at all.
See the example below how I parse the json object below.
class MyObject {
let parameters: [String]?
// it's failable because maybe json different at runtime & couldn't parse
init?(json: [String:AnyObject]) {
var key = "Parameter"
var parms = [String]()
for i in 0..<json.count {
guard let item = json["\(key)\(i+1)"] as? String else { continue }
params.append(item)
}
self.parameters = params
}
}
Now you can access the parameters array with index.
Well this could be refactored and you can get the idea how you will handle this with that library.
I am trying to read a list of objects
[
{
"name" : "Jhone",
"age" : 25
},
{
"name" : "Chris",
"age" : 24
}
]
How to handle that types of request?
You can loop through the array to access each object by its key. Assuming that array of objects is set to a variable called array
array.each { |element| puts element["name"] }
Btw, the objects are incorrectly formatted. You need a comma after each name value.
I am trying to serialize my object graph into JSON using the SwiftyJSON Library. I have a function in a BirthdayEvent class named "toJSON" which converts individual Birthday Events into swiftyJSON objects successfully.
However I am keen to have something like the following structure to the JSON:
"birthdays" : [
{
"eventId": "...",
"date": "01/01/2000",
...
},
{
"eventId": "...",
"date": "01/02/2001",
...
},
...
]
I am finding it difficult to create a JSON dictionary with the String "birthday" as the key and the array of BirthdayEvent JSON items as the value.
I have the following code:
var birthdaysJSON: JSON = JSON(self.events.map { $0.toJSON() })
var jsonOutput : JSON = ["birthdays": birthdaysJSON]
The first line successfully creates a JSON object of the array of events, but I cannot seem to use this in the dictionary literal. I get an error of "Value of type 'JSON' does not conform to expected dictionary value type 'AnyObject'.
Can you tell me where I am going wrong, or am I over-complicating this?
To create a JSON dictionary, you have to initialize the JSON object on jsonOutput just like you did with birthdaysJSON:
var jsonOutput: JSON = JSON(["birthdays": birthdaysJSON])
Can I get array of objects from assignedTags.
Example:
var data = {
label : example,
id : 1,
name : example_1
}
Auto complete shows label , but on select, when I call assignedTags I want to send array of objects back, example :
[{label : example,id : 1,name : example_1}, {label : example,id : 2,name : example_2}, ...]
How can I do it?
Use concat() to combine all of your arrays.
So its array1.concat(array2).
Then use JSON.stringify() to convert the array into a JSON object.
var jsonString = JSON.stringify(array1);
Hope this helps
push into an array somewhat like this :-
var array = [];
var data={label: example};
array.push(data);