Best way to deserialize JSON dictionary with swift? - json

I have an array column of parse dictionary objects that are in JSON. I am trying to find the best way to deserialize it And then use the information on a tableview Cell. Ive never used JSON before so thanks for the help!
Here is the Column..
so far with this line of code i can print all the containing objects, but I haven't been able to deserialize it yet.
let history: AnyObject? = poolHistory.valueForKey("serviceHistory")
print("\(history)")

SwiftyJSON is a very good library, more :
https://github.com/SwiftyJSON/SwiftyJSON

Related

What's the proper way to extract data from a google protobuff object?

I have never encountered this sort of collection or object before until now (its the response from a request to Google-Cloud-Vision API).
I wrote a class that uses the API and does what I want correctly. However the only way that I can extract/manipulate data in the response is by using this module:
from google.protobuf.json_format import MessageToJson
I basically serialized the protobuff into a string and then used regex to get the data that I want.
There MUST be a better way than this. Any suggestions? I was hoping to have the API response give me a json dict or json dict of dicts etc... All I could come up with was turning the response into a string though.
Here is the file from the github repository:
image_analyzer.py
Thank you all in advance.
The built in json module will parse the string into a dictionary, like json.loads(MessageToJson(response1)).
You can just access the fields in the message object directly, e.g.:
response1 = vision_client.face_detection(image=image)
print(response1)
print(response1.face_annotations[0].detection_confidence)

Getting inside of arrays in json / Alamofire [Swift]

I am using Alamofire for getting json of: https://randomuser.me/api/
Is there any simple way to get inside those arrays in Swift? I was trying like:
Alamofire.request(.GET,"https://randomuser.me/api/").responseJSON{
(response) -> Void in
if let json = response.result.value{
print(json["results"]["user"]["name"])
}
Thanks!
If you don't mind using a library, I'd highly suggest SwiftyJSON.
It's good to note that this library is not required and parsing JSON can be done with NSJSONSerialization.
In Swift this is currently possible only with an extension / library.
Some libraries with this feature:
SwiftyJSON
In your case, maybe a perfect solution: SwiftyJSON and Alamofire combined
Otherwise you'd need to use the NSJSONSterilization and checking each variable with safe unwrapping.

Converting a Dictionary holding dates to JSON in Swift

I have a fairly large and complex NSManagedObject that I'm manipulating within my application and sending back to a server as JSON. My plan was to do what I need to do in my application, convert the object to a Dictionary, and then send it along after calling NSJSONSerialization.dataWithJSONObject (I've also tried using SwiftyJSON, which I think is doing more or less the same thing). This was all working fine until I needed to include some dates.
Basically all of the documentation I've seen says that serialization works just fine with a certain list of object types, which does not include NSDate. Sadly, I need some dates. I should note that I am working with a dictionary of dictionaries that may have dates scattered all up and down the tree, so if I recursively run through to convert them all to strings I'm going to have to do a whole lot of copying to NSMutable dictionaries. Surely there's an easier way? I'm a bit new to Swift and iOS development and I can't help feeling like I'm either doing something wrong or that there is a built-in solution to this problem that I'm just missing. I can't be the first person who wants to send back a date as JSON. Any help would be much appreciated.
Thanks,
Alex
Apple NSJSONSerialization Class Reference says;
You use the NSJSONSerialization class to convert JSON to Foundation
objects and convert Foundation objects to JSON.
An object that may be converted to JSON must have the following
properties:
The top level object is an NSArray or NSDictionary.
All objects are instances of NSString, NSNumber, NSArray,
NSDictionary, or NSNull.
All dictionary keys are instances of NSString.
Numbers are not NaN or infinity.
Other rules may apply. Calling isValidJSONObject: or attempting a
conversion are the definitive ways to tell if a given object can be
converted to JSON data.
I think you should convert your dates to String and add them to your Dictionary. But it says; Other rules may apply. Calling isValidJSONObject: Just try to create a dictionary with your NSDate object and call the isValidJSONObject if it returns true it should be work.

How to deserialize JSON to object in Swift WITHOUT mapping

Is there a way to deserialize a JSON response to a custom object in Swift WITHOUT having to individually map each element.
Currently I am doing it manually with SwiftyJSON but it still requires me to map every field redundantly:
var myproperty1 = json["myproperty1"].stringValue
However coming from a C# background it is as simple as one line of code:
JsonConvert.DeserializeObject<CustomObject>(jsonString); //No mapping needed.
Source - http://www.newtonsoft.com/json/help/html/DeserializeObject.htm
Since I am writing many API endpoints I would like to avoid all the boilerplate mapping code that can be prone to errors. Keep in mind that my JSON responses will be multiple levels deep with arrays of arrays. So any function would need to be recursive.
Similiar question : Automatic JSON serialization and deserialization of objects in Swift
You could use EVReflection for that. You can use code like:
var user:User = User(json:jsonString)
or
var jsonString:String = user.toJsonString()
See the GitHub page for more detailed sample code
You should be able to use key value coding for this. You'd have to make your object a subclass of NSObject for KVC to work, and then you could loop through the elements of the JSON data and use setValue:forKey to assign a value for each key in the dictionary.
Note that this would be dangerous: If the target object did not contain a value for a specific key then your code would crash, so your program would crash on JSON data that contained invalid keys. Not a good thing.

Parse Simple Json Array in Play Framework

I'm sure there is a simple way to do this, but I haven't found a way to do it. How do I go about parsing a simple json array: [1] as a List[Integer] or List[String] with the play framework Json Library in scala?
All of the examples I have seen in the documentation assume you are working with an object and are accessing an attribute in the object. When I try to parse the json I get an error:
jsonResult.as[List[String]]
JsError(List((,List(ValidationError(error.expected.jsarray,WrappedArray())))))