Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

JSON .NET for Unity

Discussion in 'Assets and Asset Store' started by Dustin-Horne, Sep 13, 2013.

  1. jGate99

    jGate99

    Joined:
    Oct 22, 2013
    Posts:
    1,936
    @Dustin-Horne
    How can i deserialize json which has a property "user-token"?
    because i cant declare variable with "-" in my C# object.
    Please advise
     
  2. jGate99

    jGate99

    Joined:
    Oct 22, 2013
    Posts:
    1,936
    Another question is
    json i get have lowercase properties like "error"
    while i want my C# class to have "Error"
    How can i do that?
     
  3. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    On your class, you can use JsonProperty to specify the property names.

    Code (csharp):
    1.  
    2. public class MyObject
    3. {
    4.      [JsonProperty(PropertyName="user-token")]
    5.      public string UserToken { get; set;}
    6. }
    7.  
    By default, it is not case sensitive, so if your C# class is "Error" and your json has "error" then it will Deserialize properly. However, if you want to reserialize it and make sure you're using lowercase "error" then you'll need to use the JsonProperty attribute with PropertyName specified and use the lowercase variant (just as we did for user-token above). This will make sure it serializes with the lowercase value. If you only ever deserialize then you don't have to worry about it.[/code]
     
    jGate99 likes this.
  4. jGate99

    jGate99

    Joined:
    Oct 22, 2013
    Posts:
    1,936
    Dustin-Horne likes this.
  5. jGate99

    jGate99

    Joined:
    Oct 22, 2013
    Posts:
    1,936
    @Dustin-Horne
    I have a very interesting problem.
    I want to serialize an object in 2 different ways, same object but different ways
    - in one way i want to serialize some of its properties and some ignore,
    - and in other way i want to serialize only those properties which are not null

    so here is my object with following properties
    Id,
    Name,
    __CLASS,

    first way:
    serialize Name and _Class

    sencond way
    serialize only those which are not null (all 3 are string, so if they have value then serialize otherwise not)


    Please advise
     
  6. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    Can you explain a bit more how you want to serialize this? Do you want to serialize it as two different objects at two different times? If so, you can use a JsonConverter to just handle the two properties you want in Case #1, in Case #2 you can do the same thing... actually you could create a JsonConverter that takes an argument that tells which way to serialize it.
     
  7. jGate99

    jGate99

    Joined:
    Oct 22, 2013
    Posts:
    1,936
  8. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    I need you to explain to me the rules around when you will serialize what fields. I know scenario #2 you want to just serialize the non-null ones... that one is easy. I need to know how / when you decide to do scenario #1 where you just serialize the two fields.
     
  9. jGate99

    jGate99

    Joined:
    Oct 22, 2013
    Posts:
    1,936
    there is a bool,
    if(updated){
    serialize id
    dont serialize __class
    serialize all the properties which are not null lets say FirstName

    }

    if(updated == false){//new object in server
    dont serialize id
    serialize __class
    serialize all the properties which are not null lets say FirstName

    }
     
  10. jGate99

    jGate99

    Joined:
    Oct 22, 2013
    Posts:
    1,936
    @Dustin-Horne

    I have another problem. Here is the json
    Code (JavaScript):
    1. {"offset":0,"data":[{"prescription_6":"","created":1472581594000,"prescription_5":"","ownerId":"12EF8182-2296-5F0B-FFB0-D92B36DE3D00","__meta":"{\"relationRemovalIds\":{},\"selectedProperties\":[\"prescription_6\",\"created\",\"prescription_5\",\"prescription_4\",\"___class\",\"prescription_3\",\"prescription_2\",\"prescription_1\",\"ownerId\",\"updated\",\"objectId\",\"status\"],\"relatedObjects\":{}}","prescription_4":"","___class":"Refill","prescription_3":"","prescription_2":"Panadoll","prescription_1":"Medications","updated":1473607523000,"objectId":"E5A0336F-CD53-5A08-FFCA-8C31E9839D00","status":0}],"nextPage":null,"totalObjects":1}

    What i want is parse the json as JContainer (or anything that doesnt require a concrete class) and do something like that
    Code (CSharp):
    1.   JContainer obj = JsonConvert.DeserializeObject(json);
    2.  
    3. //Some way to get offset, nextPage and totalObjects
    4. int offset = obj["offset"].AsInt;
    5. //OR
    6. int totalObjects = int.Parse(obj["totalObjects"].value)
    7.  
    8. //then i want to get json of data property so i can finally deserialize it with concrete
    9.  
    10.             Prescription[] values  = JsonConvert.DeserializeObject<Prescription>( obj["data"].toJson);
    11.  
    I hope you can understand my requirement, please guide
     
  11. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    John, sorry I haven't gotten back to you on your Converter yet... it's actually a complicated issue because you want to selectively serialize properties and it's something that probably would be better to be done in your logic rather than a converter. I've been playing with a couple of ideas and all of them are very hacky.

    As to your second question:

    Code (csharp):
    1.  
    2.    var jo = JObject.Parse(jsonString);
    3.    var offset = jo["offset"].Value<int>();
    4.  
    5.     var totalObjects = jo["totalObjects"].Value<int>();
    6.  
    For the second part, you want an array of Prescription, so you can do it two ways:

    Code (csharp):
    1.  
    2.      var values = JsonConvert.DeserializeObject<Prescription[]>(jo["data"].ToString());
    3.  
    4.       //OR
    5.  
    6.       var values = jo["data"].ToObject<Prescription[]>();
    7.  
    The ToString() call on the JObject elements returns the JSON representation of that property.
     
  12. jGate99

    jGate99

    Joined:
    Oct 22, 2013
    Posts:
    1,936
    @Dustin-Horne
    First of all thank you very much, especially for the 2nd answer.

    As for first, Let me tell you actual problem,
    i'm using a cloud and use concrete object to save data (in that case __id is null and __class is must) and update in that case __id is must but even though __class will have value i cant seralize it otherwise cloud will reject it)

    Currently im making 2 seperate objects for this situation and thats the reason i want 1 object to handle both cases (whether secretly or with logic).

    Thanks
     
  13. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    Your best bet would be to make the fields Nullable (so if Id is an "int" field, make it Nullable<int> or int?). Then, do this:

    Code (csharp):
    1.  
    2. JsonConvert.DefaultSettings().NullValueHandling = NullValueHandling.Ignore;
    3.  
    So just leave "null" any fields that you don't want serialized. With that setting, any field that is Null won't be included in the resulting JSON which I think would solve the issue for you.
     
  14. jGate99

    jGate99

    Joined:
    Oct 22, 2013
    Posts:
    1,936
    Dustin-Horne likes this.
  15. atcae102410

    atcae102410

    Joined:
    Sep 14, 2016
    Posts:
    3
    hi everyone,
    has anyone tried Excel to Json Converter by Benzino07?
    Its great plugin and it works fine in the Editor, but when I build it for windows, it doesn't work.
    If someone has tried it and got it worked on windows, please help me in making it work on windows build.
     
  16. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    Never heard of it, but this is not the right thread to be asking in. This is the official support thread for another asset.
     
  17. Jlpeebles

    Jlpeebles

    Joined:
    Oct 21, 2012
    Posts:
    54
    the path $.[?(@>0)] appears to returning null for { "amount" : 1 } but works on http://jsonpath.com/, any idea what might be wrong?
     
  18. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    Good question, I'll have to take a look. I haven't really worked with JsonPath so I don't have any tests around it.
     
  19. Jlpeebles

    Jlpeebles

    Joined:
    Oct 21, 2012
    Posts:
    54
    It works with arrays, it looks like the expression parser is simply converting the JProperty {"amount" : 1} to a JValue which is null and skipping evaluation (QueryExpression.cs line 83). Not sure if there would be consequences with automatically gabbing values from properties in this case, or perhaps adding an implicit conversion from JProperty to JValue. There was a commit on the JsonNet repo a week ago that added $ support inside of filters which would probably fit my use case, so I might grab those changes.
     
    Last edited: Sep 18, 2016
  20. just_a_joke

    just_a_joke

    Joined:
    Apr 20, 2015
    Posts:
    13
    Hi guys,
    I purchased and imported the JSON .NET into Unity 5.3.5f1.
    But I run into the following error when tried to build Windows Store Universal 10 :-

    Assets\JsonDotNet\Source\WinRT\Converters\RT_StringEnumConverter.cs(185,37): error CS0121: The call is ambiguous between the following methods or properties: 'System.Reflection.TypeExtensions.GetFields(System.Type)' and 'Newtonsoft.Json.Utilities.TypeExtensions.GetFields(System.Type)'

    Any advice or fix to that?

    Thanks
     
  21. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    Thanks, I'll see if I can get it put in. The new commits are for JSON .NET version 9. I want to get updated from 8.x to 9.x but I have to be careful because some customers are using other assemblies that have strong links to 8.x so going to 9.x might blow that up since Unity doesn't have a way to do assembly binding redirects.
     
  22. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    Yes, make sure you delete the entire /JsonDotNet folder before you import the update. Did you just re-purchase? It looks like you have the old version in there and tried to import the new version on top of it. Unity doesn't automatically delete all of the old files so you need to have all of those old files out of there before you import the new 2.x version. The new version is precompiled DLLs to ease build times. The source is still included but it's in a separate .zip file that's part of the package.
     
  23. just_a_joke

    just_a_joke

    Joined:
    Apr 20, 2015
    Posts:
    13
    Thanks for the reply, will try to remove and re-import. And previously what I did was importing the new update without removing the old version.
     
    Dustin-Horne likes this.
  24. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    Let me know if this didn't work for some reason.
     
  25. James_FallenTreeGames

    James_FallenTreeGames

    Joined:
    Sep 30, 2016
    Posts:
    16
    Hi, thanks for the asset, we've been using this fine for some initial tests on PC + console but have hit a problem when trying to serialise a class with quaternions in it on console.

    Code (CSharp):
    1. ExecutionEngineException: Attempting to JIT compile method '(wrapper runtime-invoke) <Module>:runtime_invoke_Vector3_Quaternion* (UnityEngine.Quaternion*,intptr,intptr,intptr)' while running with --aot-only.
    2.  
    3.   at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (System.Reflection.MonoMethod*,object,object[],System.Exception&)
    4.   at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000] in <filename unknown>:0
    5. Rethrow as TargetInvocationException: Exception has been thrown by the target of an invocation.
    6.   at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000] in <filename unknown>:0
    7.   at System.Reflection.MonoProperty.GetValue (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] index, System.Globalization.CultureInfo culture) [0x00000] in <filename unknown>:0
    8.   at System.Reflection.MonoProperty.GetValue (System.Object obj, System.Object[] index) [0x00000] in <filename unknown>:0
    9.   at Newtonsoft.Json.Utilities.ReflectionUtils.GetMemberValue (System.Reflection.MemberInfo member, System.Object target) [0x00000] in <filename unknown>:0
    10.   at Newtonsoft.Json.Serialization.ReflectionValueProvider.GetValue (System.Object target) [0x00000] in <filename unknown>:0
    11. Rethrow as JsonSerializationException: Error getting value from 'eulerAngles' on 'UnityEngine.Quaternion'.
    12.   at Newtonsoft.Json.Serialization.ReflectionValueProvider.GetValue (System.Object target) [0x00000] in <filename unknown>:0
    13.   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculatePropertyValues (Newtonsoft.Json.JsonWriter writer, System.Object value, Newtonsoft.Json.Serialization.JsonContainerContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonProperty property, Newtonsoft.Json.Serialization.JsonContract& memberContract, System.Object& memberValue) [0x00000] in <filename unknown>:0
    14.   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject (Newtonsoft.Json.JsonWriter writer, System.Object value, Newtonsoft.Json.Serialization.JsonObjectContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract collectionContract, Newtonsoft.Json.Serialization.JsonProperty containerProperty) [0x00000] in <filename unknown>:0
    15.  
    I could manually serialise the parts of the Quaternion, but as we are using the AOT dll I thought this would be handled already?
     
  26. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    James, could you do me a big favor and submit a bug report to Unity? This exception actually happens for all of Unitys built in structs on Xbox one (possibly other consoles). Even more frustrating is that this bug was reported about a year and a half ago and still hasn't been fixed, so if you could report it and drop me the bug number I'll follow up.

    Now, there is a fix. I've included converters in the Newtomsoft.Json.Converters namespace to handle sll of these. By default the VectorConverter and I think the Matrix4x4Converter are enabled as those are the most common being serialized on the platform. There is also a QuaternionConverted in that namespace.

    Somewhere in your code, just one time, do:
    Code (csharp):
    1.  
    2. JsonConvert.DefaultSettings().Converters.Add(new QuaternionConverter());
    3.  
    There are also converters for Uri, Resolution and Color which includes both Color and Color32 types.
     
  27. James_FallenTreeGames

    James_FallenTreeGames

    Joined:
    Sep 30, 2016
    Posts:
    16
    Thanks for the speedy reply, very much appreciated.

    I've give the converter a go and look at raising a bug in Unity for the issue.

    Thanks again
     
    Dustin-Horne likes this.
  28. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    There's also a PDF documentation included and I have all of those converters detailed there so if you run against one that I don't have let me know and I'll get if written.
     
    James_FallenTreeGames likes this.
  29. James_FallenTreeGames

    James_FallenTreeGames

    Joined:
    Sep 30, 2016
    Posts:
    16
    Yeah, I did actually read through the documentation again before positing my original question, as I remembered from the first time of reading it that there were custom converters.

    The documentation (2.0.1) says:
    It doesn't mention QuaternionConverter, and a search for Quaternion doesn't find anything in the whole document, so I asked here :)
     
    Dustin-Horne likes this.
  30. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    Whoops! Thanks! I'll make sure I get it added to the document.
     
  31. JOKaija

    JOKaija

    Joined:
    Feb 8, 2015
    Posts:
    161
    Damn! Almost perfect, but still not!

    I'm a years away to port my game for WebGL since webgl won't work within next 5 years. Poor FPS, poor compatibility with complex code etcetc........ crashes all the time....

    AND I KNOW, there is a hundreds of coders, who will NOT change to WebGL and stick with webplayer, since webgl SUCKS!

    SO!

    I'm using Unity 5.3.6, since I need original web player for my app. It works just fantastic, BUT
    as documented, I can't use your Json for it. And I didn't find any other way to save locally game data, what will be available for new app build too.

    Is there an any change to get Newtonsoft Json version, which work with web player too?

    OR Do you, or anyone else have a knowledge about working (gameobjects etc...) Json equivalent unity package?
     
    Last edited: Oct 21, 2016
  32. jGate99

    jGate99

    Joined:
    Oct 22, 2013
    Posts:
    1,936
    @Dustin-Horne
    Is JSON.Net supports WebGL? im facing following issue when parsing json data?
    NotSupportedException: /Applications/Unity/Unity.app/Contents/il2cpp/libil2cpp/icalls/mscorlib/System.Reflection.Emit/DynamicMethod.cpp(21) : Unsupported internal call for IL2CPP:DynamicMethod::create_dynamic_method - System.Reflection.Emit is not supported.
     
  33. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    I'll see if I can get it working. Unity has we broken API implementations in Web Player that take some very specific workarounds and it's kind of nasty.
     
  34. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    It does, are you using my asset in that project and if so what version? WebGL is mapped go the /AOT/Newtonsoft.Json.dll and that was my doesn't use Reflection.Emit so either the assembly mappings have gotten hosed somehow or you're accidently using someone else's assembly.
     
  35. Ox_

    Ox_

    Joined:
    Jun 9, 2013
    Posts:
    93
    I have a problem with deserialization failing on iOS only.

    The server responds with a valid JSON like:
    Code (CSharp):
    1. {"access_token":"bhv6kxlangygzhndezq6ebw8uzpzqyqzl","expires_in":3600,"token_type":"Bearer","scope":"basic","refresh_token":"1mfviye0bqnd8ng8teyvwqhfsmbz7g","minimum_game_version_supported":1,
    2. "user_record":{"ID":"181","user_login":"login","user_nicename":"login","user_email":"login@domain.com","user_registered":"2016-01-06 18:59:47","user_status":"0","display_name":"login","email":"login@domain.com"}}
    Then I'm trying to deserialize it (this works perfectly in the editor or in desktop builds, resp.DataAsText is a string):
    Code (CSharp):
    1. UserAccessRecord record = JsonConvert.DeserializeObject<UserAccessRecord>(resp.DataAsText);
    UserAccessRecord class, I explicitly assigned each field to JSON property while trying to solve the issue:
    Code (CSharp):
    1. public class UserAccessRecord
    2. {
    3.     [JsonProperty("access_token")]
    4.     public string access_token { get; set; }
    5.     [JsonProperty("expires_in")]
    6.     public int expires_in { get; set; }
    7.     [JsonProperty("token_type")]
    8.     public string token_type { get; set; }
    9.     [JsonProperty("scope")]
    10.     public string scope { get; set; }
    11.     [JsonProperty("refresh_token")]
    12.     public string refresh_token { get; set; }
    13.     [JsonProperty("minimum_game_version_supported")]
    14.     public int minimum_game_version_supported { get; set; }
    15.     [JsonProperty("user_record")]
    16.     public UserRecord UserRecord { get; set; }
    17.     public override string ToString()
    18.     {
    19.         return JsonConvert.SerializeObject(this, Formatting.Indented);
    20.     }
    21. }
    In the end there's a UserAccessRecord with null and zero fields only.

    Code (CSharp):
    1. {
    2.   "access_token": null,
    3.   "expires_in": 0,
    4.   "token_type": null,
    5.   "scope": null,
    6.   "refresh_token": null,
    7.   "minimum_game_version_supported": 0,
    8.   "user_record": null
    9. }
    Any ideas what could be wrong? Thank you!
     
  36. jGate99

    jGate99

    Joined:
    Oct 22, 2013
    Posts:
    1,936
    Ok i rememebr the issue, i'm using another plugin which forced me to replace your version (updated) with their and now this is causing issue. I talked to auther few weeks ago about this issue and looks like this time he has to take it seriously to support your updated version.
    https://www.assetstore.unity3d.com/en/#!/content/29704
     
  37. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    Yep. :). IL2CPP is stripping the setters from your properties. They probably are only used via deserialization. You'll need to either add your class to a link.xml file or add [Preserve] attributes to your properties.
     
    Ox_ likes this.
  38. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    John, you were the second person yesterday with that same problem and same asset. The author should provide source code so his asset can be recompiled with an updated reference or he should make sure he's not requiring a specific version of json .net.
     
    Last edited: Oct 23, 2016
    jGate99 likes this.
  39. JOKaija

    JOKaija

    Joined:
    Feb 8, 2015
    Posts:
    161
    Thank's but too late. I don't need it anymore.

    I did try unitys original JSonUtility's tojson and fromjson routines. It seems, they work right now as required!

    When Unity fixed that? I remember, that I fight too much with them year or two ago.

    Hovewer, I don't need anymore 3rd party json/de-/serializers. Unity did it!
    Full hierarchy at once. No problems with new builds either. I'm satisfied.
     
  40. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    Oh yeah they've improved it. It doesn't support some complex things like Dictionaries and it's not flexible, but will offer better performance if it works for you, so if it works in your scenario it's definitely the way to go. Thanks for letting me know!
     
  41. JOKaija

    JOKaija

    Joined:
    Feb 8, 2015
    Posts:
    161
    np.

    I'm glad I don't need any dictionares. I use only List<t> method almost for everything. Only Djikstra routine, what I use for finding a way for my workers via user made roads uses it, but I don't need ever save that. It uses dicts. internally only.

    Jari
     
    Dustin-Horne likes this.
  42. jGate99

    jGate99

    Joined:
    Oct 22, 2013
    Posts:
    1,936
    @Dustin-Horne

    What if i want to serialize an int property of class when int is not 0. If its other than 0 then serialize, otherwise ignore.

    Thanks
     
  43. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    Hey John, sorry I either missed or didn't get an email notification for your post. Is there any particular reason you'd want to do this other than to make your json smaller? You can do it but you'd have to write a custom JsonConverter to handle it.
     
  44. jGate99

    jGate99

    Joined:
    Oct 22, 2013
    Posts:
    1,936
    Yes, one reason is making it small.
    Is there any tutorial like approach with conditional json creator?
    Thanks
     
  45. adamt

    adamt

    Joined:
    Apr 1, 2014
    Posts:
    116
    I'm not clear if this is an issue with JSON.Net itself or the port for Unity, but I've never been able to gracefully handle exceptions when deserializing JSON. Looking at the official website, it seems like this code should do exactly what I want it to do:

    Code (CSharp):
    1. Dictionary<string, JToken> response = JsonConvert.DeserializeObject<Dictionary<string, JToken>>(responseString, new JsonSerializerSettings
    2. {
    3.     Error = delegate(object sender, ErrorEventArgs args)
    4.     {
    5.         Debug.LogErrorFormat("JSON Serialization error: {0}; {1}", args.CurrentObject, args.ErrorContext.Error.Message);
    6.         args.ErrorContext.Handled = true;
    7.     },
    8.     DateTimeZoneHandling = DateTimeZoneHandling.Utc
    9. });
    However, if my source JSON contains an integer value greater than Int32.MaxValue that is being deserialized as a standard C# int type (in my case, the offending integer was 9,999,999,999), JSON.Net throws an OverflowException and never hits the Error delegate. I can surround the deserialization in a try/catch statement, but 1.) that seems to defeat the purpose of the Error delegate; and 2.) I lose information on what property caused the exception (we have a lot of data getting deserialized, so it's impractical to dig through it all to try and find the issue).

    Any ideas?
     
  46. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    The easiest thing to do if you're interested in keeping it small is to use the DefaultValueHandling setting on JsonSerializerSettings. The following would need to be executed just once somehwere:

    Code (csharp):
    1.  
    2. JsonConvert.DefaultSettings().DefaultValueHandling = DefaultValueHandling.Ignore;
    3.  
    This will skip writing any properties that have their default value (such as 0 for an int or false for a bool or null for anything else). That is your best approach.

    A custom JsonConverter can be written if you need to handle it on a case by case basis... here is the JsonCovnerter documentation:
    http://www.newtonsoft.com/json/help/html/CustomJsonConverter.htm

    You can also unzip the source in my asset and look in the Newtonsoft.Json/Converters folder. Take a look at the VectorConverter for example which just serializes certain properties. In your case you would enumerator the properties and check the value and only write the property if you needed to.
     
  47. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    Let me dig into this and take a look. There is special handling in the way number types are determined and the overflow error would be thrown in that class which is where it determines, for instance, whether to use a BigInteger or int or long type. (BigInteger is .NET 4.x but it will be supported when Unity finishes updating the .NET profile).
     
  48. adamt

    adamt

    Joined:
    Apr 1, 2014
    Posts:
    116
    Thanks, Dustin.

    To be clear, I still would like JSON.Net to throw an error in this case, not try to coerce the type into BigInteger, since I'm not expecting that field to be a BigInteger (our game designer used that number to put it out of reach while testing something, but didn't realize it would break the deserializer). I just want it to happen gracefully/using the Error delegate flow instead of throwing what looks like an unhandled exception.
     
  49. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    Absolutely, it's an internal method that parses a numeric string from the json and puts it into the appropriate data format, but that's not necessarily the type that gets returned. BigInteger also isn't supported in Unity Editor or any platform other than UWP at the moment so you won't have to worry about that, you'll never see it.
     
  50. adamt

    adamt

    Joined:
    Apr 1, 2014
    Posts:
    116
    Any updates on this? I can monkey patch it, but I usually try to avoid that to limit the issues that tend to crop up when updating libraries to new releases.