Converting a Dictionary holding dates to JSON in Swift - json

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.

Related

Django - serialize complex context structure with models and data

In django view I want to be able to serialize whole context, that is usually used to send to template (typically by calling render and passing locals).
I want to experiment with SPA+API and possibilities to go forward with and I'd like to create function, that would serialize locals to json and return it as json response.
Now problem is, that locals is typically mix of lists, dists and querysets of models.
I can serialize models using django.core.serializers or using django-rest-framework. I can serialize dict with primitive types using json library, but I don't know any simple way how to do mix of those.
Ideal would be way to go through locals dictionary and replace all found models with their serialized representations and then put it all together, maybe even specify before what serializer (in sense of drf) to use for which model. But I really don't want to reinvent wheel in case it already exists.
Anoher question is - is this even a good idea to try to do this? Return json context as alternative to server side rendering? I am in prototyping stage so I am still thinking of how to move forward and any input in the area is appreciated.
I would recommand to go with DRF
ModelSerializer will return a Json encoded array of model
Serializer with DictField will return a Json encoded dict
Serializer with ListField will return a Json encoded list
You can create Serializer with field is another Serializer for nesting purpose.
https://www.django-rest-framework.org/api-guide/fields/#composite-fields
https://www.django-rest-framework.org/api-guide/serializers/#dealing-with-nested-objects
For your' question is this a good idea, i would said :
If you push data to an external source (not django) it's fine
If you push data to django template it's a bad idea, you loose a lot of django power :(

VBJSON for VB6 how to serialize object returned from Parse routine

So there is a nice library for VB6 JSON parsing. HERE
but i actually used one that built on the original and optimized. HERE
Essentially I'm using the parser to deserialize the json i get from a web service. I need to update some values, and resend to the server. Using the Collection/Dictionary objects made it very easy. But now, How do i take those objects and serialize them to a JSON string? is there a library for that?
thanks you for your help.
There are quite a few JSON parser/serializer/DOM classes written in VB6. Perhaps you might want to consider one of those instead. E.g.:
JsonBag, Another JSON Parser/Generator

Parsing JSON in VBA, without any external library

I'm really at my wit's end here... I'm using VB-JSON Parser (http://www.ediy.co.nz/vbjson-json-parser-library-in-vb6-xidc55680.html) and I have the following array :
[{"timestamp":1410001952,"tid":2834225,"price":"483.77"}]
The documentation is really minimal and I have no clue whatsoever of how to access the array, been searching for several hours now on how to resolve this.
How can I get the "price" value? I know that i can use .item("price") when there is no array but I don't know what to do when there's an array and there is no name before it.
First have a look at Parsing JSON in Excel VBA
It explains the JScript way of parsing JSON string.
Browsing through the net, I found it really hard to get a complete VBA based JSON parser.
Some options are available in the VB version and then there are few online parsers who promise to parse JSON and convert them in Excel. These ones work fine with simple JSON data structure. But once you feed in a complex data set with nested arrays and structures, they simply fail.
Using JavaScript features of parsing JSON, on top of ScriptControl, we can create a parser in VBA which will list each and every data point inside the JSON. No matter how nested or complex the data structure is, as long as we provide a valid JSON, this parser will return a complete tree structure.
JavaScript’s Eval, getKeys and getProperty methods provide building blocks for validating and reading JSON.
Coupled with a recursive function in VBA we can iterate through all the keys (up to nth level) in a JSON string. Then using a Tree control (used in this article) or a dictionary or even on a simple worksheet, we can arrange the JSON data as required.
Here, you can find a complete VBA example.
There is a JSON serializer in .NET: http://msdn.microsoft.com/en-us/library/system.runtime.serialization.json

Debugging json4s read deserialization errors

I am attempting to consume an API that I do not have control over which is somewhat poorly documentented and somewhat inconsistent. This means that sometimes, the API returns a different type than what is documented or what you would normally see. For this example, we'll look at a case when an array was returned in a place where I would normally see a string. That makes a crappy API, but my real problem is: How can I more easily track those things down? Right now, the errors look something like this:
No usable value for identifier
Do not know how to convert JArray(List(JString(3c8723eceb1a), JString(cba8849e7a2f))) into class java.lang.String
After deciphering the problem (why JValue::toString doesn't emit a JSON string is utterly perplexing to me), I can figure out the API returned an array when I made my case class only able to deal with Strings. Great. My issue is that finding this discrepancy between my object model and the contents of the JSON seems significantly more difficult than it should be.
Currently, this is my workflow for hunting down decoding errors:
Hope bad data has some sort of identifying marker. If this is not true, then it is way more guesswork and you will have to repeat the following steps for each entry that looks like the bad bits.
Go through the troubles of converting the JArray(List(JString(...), ...)) from the error message into valid JSON, hoping that I encode JSON the same way at the API endpoint I got the data from does. If this is not true, then I use a JSON formatter (jq) to format all data consistently.
Locate the place in the source data where the decoding error originates from.
Backtrack through arrays and objects to discover how I need to change my object model to more accurately represent what data is coming back to me from the API.
Some background: I'm coming from C++, where I rolled my own JSON deserialization framework for this purpose. The equivalent error when using the library I built is:
Error decoding value at result.taskInstances[914].subtasks[5].identifier: expected std::string but found array value (["3c8723eceb1a","cba8849e7a2f"]) at 1:4084564
This is my process when using my hand-rolled library:
Look at the expected type (std::string) compared with the data that was actually found (["3c8723eceb1a","cba8849e7a2f"]) and alter my data model for the path for the data in the source (result.taskInstances[914].subtasks[5].identifier)
As you can see, I get to jump immediately to the problem that I actually have.
My question is: Is there a way to more quickly debug inconsistencies between my data model and the results I'm getting back from the API?
I'm using json4s-native_2.10 version 3.2.8.
A simplified example:
{ "property": ["3c8723eceb1a", "cba8849e7a2f"] }
Does not mesh with Scala class:
case class Thing(property: String)
The best solution would be to use Try http://www.scala-lang.org/api/current/#scala.util.Try in Scala, but unfortunately json4s API cannot.
So, I think you should use Scala Option type http://www.scala-lang.org/api/current/#scala.Option .
In Scala, and more generally in functional languages, Options are used to represent an object that can be there or not (like à nil value).
For handle parsing failures, you can use parse(str).toOption, which is a function that return an Option[JValue], and you can doing a pattern matching on the resulting value.
For handling extraction of data extraction into case classes, you can use extractOpt function, to do pattern matching on the value.
You can read this answer : https://stackoverflow.com/a/15944506/2330361

serviceStack.Text .ToJson extension method option to output empty array for null list<T> property

There's a bit of work to set the stage, so please bear with me...
I'm using knockout to databind a rather deeply nested data structure. When I retrieve the data from the database (from MongoDB using the Mongo C# Driver) there are nested properties (of type List<T>) that aren't populated and are returned as null. I'm using the ServiceStack.Text .ToJson extension method to serialize this data structure to JSON that gets passed to the client for knockoutMapper to convert into my observable viewModel. All goes well, except for the List<T> properties that were null on the server. Since they arrive at the client with a null value, knockoutMapper just makes them observables instead of observableArrays. Now for the question... Is there any way to tell ServiceStack that I want any property of type List<T> that is empty to be serialized as an empty array? I've dug through the JsConfig object to find a setting that looks like it might help but haven't had any luck. Am I missing something in JsConfig or is this something I should be doing in knockoutMapping on the client?
EDIT: Just a note - this is a side project where I'm learning 3-4 new technologies and I have come to see how absurd it is to retrieve JSON from Mongo, use the C# driver to convert this to a POCO to work with it on the server, then to use serviceStack to serialize the POCO as JSON. I plan on changing this with a straight through shot of just JSON, but this is a learning process for me.