I’m saving my save files using jsonconvert to serialize, since I have a lot of dictionaries and stuff. This is working okay but why am I having to cast integers from long back to int? Currently I get a cast error if I try using the data I read unless I convert it first after reading the variable (long) and then using Convert.ToInt32(variable).
Don‘t tell, show. We need to see the code!
That’s not enough details to make any kind of suggestion. What exactly does your code look like and what does the input json look like (we don’t need the full json, but the context and format is important). So how is that value actually serialized? As a json number or a json string? What C# types do you actually use with json convert? When you use generic “object” types, have you actually checked as which type it is deserialized?
Well I was going to dig through all my code and paste relevant stuff but I found that json appears to serialise float as double, which was causing the problem. So all I had to do was cast (float)(double) when reloading my save data and it’s working without the error
Yes, JSON only has 6 different datatypes: object
, array
, string
, number
, bool
and null
. JSON itself doesn’t specify a precision for the “number” but recommends to support at least double precision floats. That’s why almost all parsers use double values. That’s also the default in javascript where JSON came from. So when you parse json without any type information on the C# side, you would always get doubles.
My SimpleJSON parser does not do the normal C# object mapping like most other parsers but simply parse the json data into specialized classes. Those implement various casting and conversion operators and properties to simplify the usage of the data. So everything can be seen as a JSONNode and you would get implicit casting. It even automatically parses strings to numbers and offers double and float access. Since every class is declared partial, it’s easy to extend them with additional conversion methods and operators. I made an extension file for some Unity types. Such extensions just need to sit next to the SimpleJSON.cs.