Convert string representation of JSON to JSON - swift

I have an odd question.
I have a string named string, {"reply": "", "emoji": ":)", "time": "3"}
Now obviously because this is a string, I cannot access it with string["time"].
I need to convert it to an array (or JSON), but I cannot figure out how.
I tried SwiftyJSON
let b = JSON(string)
print(b["comment"]) #"null\n"
I tried JSONSerialisation, but that seemingly failed as well.
Any help would be appreciated.
I am using Alamofire to retrieve the JSON, when I use .responseString, it contains everything, but .responseJSON is empty, and I don't know why.

Here's a quick-and-dirty solution with JSONSerialization that should get your started:
let string = "{\"reply\": \"\", \"emoji\": \":)\", \"time\": \"3\"}"
let json = try! JSONSerialization.jsonObject(with: string.data(using: .utf8)!, options: .allowFragments) as! [String: String]
print(json["time"])
Your actual code should have more error checking, of course.

Related

Conversion of JSON String to Object always returns nil

I'm fairly new to this. Anyway, here we go:
I have JSON data that comes from an API. For the sake of this question, I have simplified it greatly. You can run the following code in a Playground.
import UIKit
struct Book: Codable {
let image: String
}
// this comes from my API
let jsonString = "{ \"image\" = \"someURL\" }"
print(jsonString) // { "image" = "someURL" }
// convert String to Data
let jsonData = jsonString.data(using: .utf8)
// decode data (in my project, I catch the error, of course)
let decoder = JSONDecoder()
let decodingResult = try? decoder.decode(Book.self, from: jsonData!)
print(decodingResult) // nil
As you can see, I'm trying to decode my JSON-String into an Object (my Struct), but the Decoder always returns nil.
Can someone point me in the right direction?
Thank you.
Your current jsonString isn't a proper JSON. Change it to "{ \"image\": \"someURL\" }", and it should work. For more information on JSON syntax, check this manual.

json array parse return nil in swift 5

I have an json. In json there is multiple array. Here is my json...
["city": imrankhan136260#gmail.com,
"geofence_DEMRAhighway": {"type": "Polygon",
"coordinates":[[[90.45232332650568,23.714463300877014],[90.4532990923671,23.712264209703946],[90.45997933551394,23.714532021878767]]]}]
I have use bellow code get data ,it returns correct value
let city = myjson?["city"] as? String
print("city-->",city) // it returns imrankhan136260#gmail.com
But when it use bellow code get from geofence_DEMRAhighway key which returns nil. here is my code to get array
let geofence_BABUBAZARbridge = myjson?["geofence_BABUBAZARbridge"] as? [String: Any]
What is the wrong with the code. please help me to parse the json
This json is not filly correct.
It's starts from "[", but usualy {...} uses to map it to asociative array.
But if it works, you can still use it.
So, coordinates is not a string. You have to escape it, and it will see as
{\"type\": \"Polygon\",\r\n\"coordinates\":[[[90.45232332650568,23.714463300877014],[90.4532990923671,23.712264209703946],[90.45997933551394,23.714532021878767]]]}
If you can not change the format, then you shoud read it as JSonObject and convert it to string:
JSONSerialization.jsonObject(.....)
And then use
myjson?["city"]["type"]
You can try this:
JSONSerialization.data(withJSONObject: myjson?["city"], options: [])
myjson?["city"] will return an object, and JSONSerialization.data will convert it to string
And so one.

HTTP Response String to 2D Swift Array

I am wandering if anyone has done anything similar to this. I make a http request and the response is a two dimensional array, for example,
[["Column1","Column2","Column3","Column4"],["1","2","3","4"]]
I am trying to convert the "text/array" in the http response to a 2D array in Swift. Has anyone done anything like this?
I understand that I can have the http response come back in the JSON format and the use of JSONDecode, but that is not what I want to do in this particular case.
try this:
let responseString = "[[\"Column1\",\"Column2\",\"Column3\",\"Column4\"],[\"1\",\"2\",\"3\",\"4\"]]"
let data = responseString.data(using: .utf8)!
if let output : [[String]] = try! JSONSerialization.jsonObject(with: data, options: []) as? [[String]]{
print(output)
}
output:
[["Column1", "Column2", "Column3", "Column4"], ["1", "2", "3", "4"]]

Convert String to NSDictionary by ignoring string literal

I'm getting dictionary value from server in form of String. Now when I try to use that String, it contains \ before ".
I get below value from my web service:
“\”{\\\”111\\\”:\\\”abc\\\”, \\\”222\\\”:\\\”xyz\\\”}\”
I'm trying to convert this string to NSDictionary. Can you please some one guide me for this. Which is the easiest way to convert this to NSDictionary. My current code is as below, but it's not working
var permValue = perm.value?.stringByReplacingOccurrencesOfString("\\", withString: "")
let data = permValue?.dataUsingEncoding(NSUTF8StringEncoding)
if let dict = try! NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary{
print("Permission Dictionary : \(dict)")
}
I'm getting an error while converting data to NSDictionary.
Please help. Any help will be appreciated

Swift: How to convert string to dictionary

I have a dictionary which i convert to a string to store it in a database.
var Dictionary =
[
"Example 1" : "1",
"Example 2" : "2",
"Example 3" : "3"
]
And i use the
Dictionary.description
to get the string.
I can store this in a database perfectly but when i read it back, obviously its a string.
"[Example 2: 2, Example 3: 3, Example 1: 1]"
I want to convert it back to i can assess it like
Dictionary["Example 2"]
How do i go about doing that?
Thanks
What the description text is isn't guaranteed to be stable across SDK versions so I wouldn't rely on it.
Your best bet is to use JSON as the intermediate format with NSJSONSerialization. Convert from dictionary to JSON string and back.
I created a static function in a string helper class which you can then call.
static func convertStringToDictionary(json: String) -> [String: AnyObject]? {
if let data = json.dataUsingEncoding(NSUTF8StringEncoding) {
var error: NSError?
let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error) as? [String: AnyObject]
if let error = error {
println(error)
}
return json
}
return nil
}
Then you can call it like this
if let dict = StringHelper.convertStringToDictionary(string) {
//do something with dict
}
this is exactly what I am doing right now. Considering #gregheo saying "description.text is not guaranteed to be stable across SKD version" description.text could change in format-writing so its not very wise to rely on.
I believe this is the standard of doing it
let data = your dictionary
let thisJSON = try NSJSONSerialization.dataWithJSONObject(data, options: .PrettyPrinted)
let datastring:String = String(data: thisJSON, encoding: NSUTF8StringEncoding)!
you can save the datastring to coredata.