Post one JSON object as value in Swift - json

I need to post only one json object as value.
Here is my code:
let jsonObject: [String: Any] = [
"data": ["user_token":"firebase_token"]
]
This code output is:
["user_token": "f4Vv2GLobhY:APA91bGz5b8M4pTqHnEeATeDSbQeq9T1VJYMS8mdX3OunJwgu5plfqVDsjYGxnNda22Drbmq7fXYyCSW1_4K69sq8kqK8hgpKbB2KuBAMGlPL-SIC8xWfazby-RnrdmBKQR6fpU8_1K_"]
The problem I'm facing is that the server wont accept this parameter because it's an array
the string should not be "[ .... .
but should be: "{ ...
So when I try to modify my code to this:
let jsonObject: [String: Any] = "data": {"user_token":"firebase_token"}
To give me the desired output I get compiler errors.
Any suggestions?

Change your type to dictionary of dictionary like
let jsonObject: [String:[String: String]]
and then encode it
let jsonObject: [String:[String: String]] = ["data": ["user_token":"firebase_token"]]
let encoder = JSONEncoder()
let data = try encoder.encode(jsonObject)

Related

Swift JSON parsing with no particular structure

I have a JSON object of this type, very pratical do loop (for each key => value)
It's like JSON of JSON
But I'm not able to decode it in Swift.
I'm trying to know if this type of data is decodable in Swift.
If it would be easy for you, could you please help to decode it? In an array for example.
{"1":{"1":"some text"},"2":{"1":"some text","2":"some text","3":"some text","4":"some text"},"3":{"1":" some text","2":"some text","3":"some text"},"4":{"1":"some text","2":"some text"},"5":{"1":"some text"},"6":{"1":"some text","2":"some text","3":"some text"}}
let jsonDict = json_text
let jsonDictData = jsonDict.data(using: .utf8)!
let object = try? JSONSerialization.jsonObject(
with: jsonDictData,
options: []
)
// Cast to a Swift Dictionary
let dict = object as? [AnyHashable:Any]
// Cast to an NSDictionary
let nsDict = object as? NSDictionary
print(nsDict)
it returns nil
Finally, I parse it by myself.
With .components(separatedBy: "},")
and .components(separatedBy: "\",\"")
and sweeping some characters with .replacingOccurrences(of: pattern, with: "")
pattern id for example pattern = "\"1\":\""

My Json string is not decoding using JSONSerialization.jsonObject()

I'm receiving a valid Json string from my HTTP request which looks like this
"[{
"id”:10,
"user_id":"77da74e6-3e03-403d-9c1a-91f231233515”,
"friend_user_id":"fc879bf5-c53d-4a4e-b3a4-dab7a8266a2r”,
"name":"Tommie Smith”,
"type":"active”,
"created_at":"2018-05-02 14:53:09",
"updated_at":"2018-05-02 14:53:09",
"friend_user":{
"id":"fc879bf5-c53d-4a4e-b3a4-dab7a8266a2r",
"first_name”:”Allen”,
"last_name”:”Williams”,
"email”:”allen.williams#example.org",
"date_of_birth":"1996-03-05 00:00:00",
"created_at":"2018-05-02 14:53:07",
"updated_at":"2018-05-02 14:53:07",
"deleted_at":null
}
},
{
"id”:11,
"user_id":"77da74e6-3e03-403d-9c1a-91f231233515”,
"friend_user_id":"96990d13-372e-46f7-9187-94988954455b”,
"name":"Mr. Thomas Atkins”,
"type":"not",
"created_at":"2018-05-02 14:53:10",
"updated_at":"2018-05-02 14:53:10",
"friend_user":{
"id":"96990d13-372e-46f7-9187-94988954455b",
"first_name”:”Trevor”,
"last_name”:”Wright”,
"email”:”trevor.wright#example.net",
"date_of_birth":"1983-07-27 00:00:00",
"created_at":"2018-05-02 14:53:08",
"updated_at":"2018-05-02 14:53:08",
"deleted_at":null
}
}]"
I know that this is what I'm receiving as I'm using the following code to return a string with my data
let string = String(data: data, encoding: String.Encoding.utf8)
However, when I use the code below to parse my data, json returns nil
let json = try JSONSerialization.jsonObject(with: data) as? [String: AnyObject]
What is wrong with this statement?
Please (learn to) read the JSON, it's pretty easy. There are only 2 (two!) different collection types:
{} is dictionary, in Swift [String: Any].
[] is array, in Swift [Any] but in most cases an array of dictionaries [[String: Any]].
so the JSON is clearly an array. In Swift 3+ a JSON value is never AnyObject
let json = try JSONSerialization.jsonObject(with: data) as? [[String: Any]]
Note:
The mistaken double quotes are not the error reason, otherwise jsonObject(with would throw an error

swift byte[] in json object

I'm trying to serialize json object like this
let jsonObject: [String: Any] = [
"Description":problemDescription.text!,
"Photo": byteArray
]
let jsonData = try! NSJSONSerialization.dataWithJSONObject(jsonObject, options: .PrettyPrinted)
but I'm getting this type of error:
swift 2 argument type string any does not conform to expected type any object.
Any ideas?
update: It seems that when I'm printing json object after this line
let jsonData = try! NSJSONSerialization.dataWithJSONObject(jsonObject, options: .PrettyPrinted)
that that conversion to byte[] occurs itself. At least seems that way in console debug.

Iterate over AnyObject. Error: Type 'AnyObject' does not conform to protocol 'SequenceType'

I'm using Alamofire to get a data from a JSON file. Example of the output:
[{"image_name":"vacation"},{"image_name":"graduation"}]
I have a problem when I try to access the information from the JSON output.
Alamofire.request(.GET, url).responseJSON { (response) -> Void in
if let JSON = response.result.value {
for json in JSON{
print(json)
}
}
The problem I have is that my JSON output is an AnyObject and I cannt iterate over an AnyObject. If I do the following:
print(JSON[0]["image_name"])
Then I can see the output correctly. How can I iterate over an AnyObject?
You may need to explicitly state the type of JSON as an array of dictionaries:
if let JSON = response.result.value as [[String : AnyObject]] {
// ...
}

Creating a certain JSON data structure in Swift

For backend communication, my app requires a method to create a certainly structured JSON, and thats where i struggle.
The created JSON is supposed to look like this:
{
"data": {
"color":"yellow",
"size":"big"
}
}
Serializing a Dictionary with the required Data does not really seem to have the option to format the content properly, my best results look like this:
Optional({
Kategorie = Strassenschaeden;
PLZ = 46282;
Strasse = Erftweg;
Unterkategorie = Schlagloch;
})
I didnt find any helpful weblinks for my problem, and since im new to Swift and its documentation Im kinda stuck at the moment.
So my questions are:
Whats the preferred data structure for my JSON data (Dictionary/Array) and how do I create a JSON that is well-formated?
Thanks in advance :)
Edit: This is the interesting part of what i have used to achieve my "best result":
var data: [String: String] = ["Kategorie": "\(Kategorie)", "Unterkategorie": "\(Unterkategorie)", "Strasse": "\(Strasse)","PLZ": "\(PLZ)"]
self.post(data, url: "http://*************") { (succeeded: Bool, msg: String) -> () in
var alert = UIAlertView(title: "Success!", message: msg, delegate: nil, cancelButtonTitle: "Okay.")
func post(params : Dictionary<String, String>, url : String, postCompleted : (succeeded: Bool, msg: String) -> ()) {
var request = NSMutableURLRequest(URL: NSURL(string: url)!)
let JSONData:NSData = NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions.PrettyPrinted, error: &err)!
var json = NSJSONSerialization.JSONObjectWithData(JSONData, options: nil, error: &err) as? NSDictionary
println(json)
Here
let JSONData:NSData = NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions.PrettyPrinted, error: &err)!
var json = NSJSONSerialization.JSONObjectWithData(JSONData, options: nil, error: &err) as? NSDictionary
you are converting the params dictionary to JSON data – and then you convert the
JSON data back do a dictionary! What you probably want is to create a string
from the JSON data:
let jsonData = NSJSONSerialization.dataWithJSONObject(params, options: .PrettyPrinted, error: &err)!
let json = NSString(data: jsonData, encoding: NSUTF8StringEncoding)!
println(json)
Remarks:
Properties and variables should have names starting with lower case letters, e.g.
jsonData.
The explicit type annotation :NSData is not needed here, the Swift compiler can
infer the type automatically.
The option can be given as .PrettyPrinted instead of NSJSONWritingOptions.PrettyPrinted, the compiler infers the enumeration type
automatically.
Instead of forced unwrapping with ! you should use optional binding to check
for success.
Just an itch, that no one here recommend swiftyJSON for working with JSON in Swift.
Try it, you will lose your pain of dealing with JSON.
https://github.com/SwiftyJSON/SwiftyJSON
To Read JSON
let jsonData = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
let jsonObject = JSON(data: jsonData!)
To Write JSON
let jsonString = jsonObject.rawString()