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.
Related
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\":\""
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)
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
When I converting Json string to dictionary in swift I got the Issue:Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
I don't know to fix the issue please give idea for fix the issue.Here I gave my code what i am tried..
The method for converting Json string to dictionary is,
func convertToDictionary(from text: String) throws -> [String: String] {
guard let data = text.data(using: .utf8) else { return [:] }
let anyResult: Any = try JSONSerialization.jsonObject(with: data, options: [])
return anyResult as? [String: String] ?? [:]
}
The Json String is: "[{\"propertyId\":\"1\",\"inspectionTemplateId\":1118,\"value\":[{\"widgetControllerId\":141,\"value\":\"Flood Summary Name\"},{\"widgetControllerId\":142,\"value\":\"Did the property flood?\"},{\"widgetControllerId\":143,\"value\":\"no\"}]}]"
And the Usage of method was:
let jsonString = NSString(data: responseObject as! Data, encoding: String.Encoding.utf8.rawValue)!
print(jsonString)
do {
let dictionary:NSDictionary = try self.convertToDictionary(from: jsonString as String) as NSDictionary
print(dictionary)
} catch {
print(error)
}
Read the error gentleman. Error is 'allow fragments not set'.
Just Just just set .allowFragments.
That's it. (Make sure response is not malformatted)
JSONSerialization.jsonObject(with: data!, options: .allowFragments)
You can try this:
let str = "[{\"propertyId\":\"1\",\"inspectionTemplateId\":1118,\"value\":[{\"widgetControllerId\":141,\"value\":\"Flood Summary Name\"},{\"widgetControllerId\":142,\"value\":\"Did the property flood?\"},{\"widgetControllerId\":143,\"value\":\"no\"}]}]".utf8
let json = try! JSONSerialization.jsonObject(with: Data(str), options: [])
print(json)
This type of issue can also occur if you have a misconfigured server or your server is unreachable. If you receive this type of error from JSON deserialization you may try converting the data to a string and print it out. It may reveal an error like "502 Bad Gateway"
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()