Search Unity

  1. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

JSON .NET for Unity

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

  1. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    I'm pleased to announce that due to a recent agreement, JSON .NET for Unity is now free! I've submitted a request to the asset store to change the price and asked for expedition. In the meantime, you can download JSON .NET for Unity from GitHub. You'll have to add a reference to UnityEngine.dll and compile yourself for now.

    https://github.com/ianmacgillivray/Json-NET-for-Unity

    I will continue to offer support for existing customers.
     
  2. jGate99

    jGate99

    Joined:
    Oct 22, 2013
    Posts:
    1,180
    Congrats.
    Agrement with Unity?
     
    Dustin-Horne likes this.
  3. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    Thanks! And no, and due to nda I don't know that I can share that information just yet.
     
    jGate99 likes this.
  4. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    The asset store has updated and the package is now listed as Free. Enjoy!

    http://u3d.as/5q2
     
  5. layola

    layola

    Joined:
    Aug 6, 2013
    Posts:
    94
    how to decode this json file? json embed json,@Dustin-Horne

    {
    "error": 0,
    "message": "",
    "result": {

    "extra": "{\"list\":[{\"part\":\"fughs0015_1\",\"json\":\"/Server/user/ehouseshow/globalMaterial/7131/fughs0015_1_Mat.json\",\"other\":\"\"}]}" }
    }


    and I got this error

    Error while processing task:
    Newtonsoft.Json.JsonSerializationException: Error converting value "{"list":[{"part":"fughs0015","json":"/Server/user/ehouseshow/globalMaterial/7131/fughs0015_Mat.json","other":""}]}" to type 'com.ehouseshow.ExtraMaterials'. ---> System.Exception: Could not cast or convert from System.String to com.ehouseshow.ExtraMaterials.
    at Newtonsoft.Json.Utilities.ConvertUtils.EnsureTypeAssignable (System.Object value, System.Type initialType, System.Type targetType) [0x00064] in g:\lib\jsondotnet\jsondotnet\JsonDotNet\Source\Utilities\ConvertUtils.cs:453
     
  6. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    Your Extra property in whatever you're deserializing to will need to be of type "string". Then you'll need to deserialize it separately. Otherwise you'll have to create a custom JsonConverter to handle it because your Json has that part of the data escaped so it's treated is a literal string.
     
  7. layola

    layola

    Joined:
    Aug 6, 2013
    Posts:
    94
    hi,be of type "string" is also got error!
     
  8. jGate99

    jGate99

    Joined:
    Oct 22, 2013
    Posts:
    1,180
    Another problem

    Lets say i have a json which can come in different formats, and i want to know when

    color is a string
    {
    color : "#1312231"
    }

    or color is an object
    {
    color : {

    }
    }

    or when color is an array
    {
    color : []
    }

    Please advise?
     
  9. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    In this case, you'll have to use JObject.Parse(jsonString), then use obj["color"] to access that property... and manually do the checking.
     
  10. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    Where is this JSON coming from? I think you're getting an invalid json string.
     
  11. jGate99

    jGate99

    Joined:
    Oct 22, 2013
    Posts:
    1,180
    It was an example json (so invalid)

    i didnt want to check after getting value because of performance, but i think now only solution is to do that as u said.
    I thought (maybe im wrong), JToken/JObject already know the type of value whether string or float?
     
  12. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    That Invalid Json remark was a reply to a different poster. :)

    And yes, there is a TokenType specified, I just can't recall if it's internal or not... I can check but it'll be a bit.
     
  13. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
  14. puzzlekings

    puzzlekings

    Joined:
    Sep 6, 2012
    Posts:
    393
    Hi Dustin

    Thanks for the updated library and congrats on the deal.

    Just testing out serialisation of basic types and when I use it for Color and call
    JsonConvert.SerializeObject(this);

    I get this error:
    JsonSerializationException: Self referencing loop detected for property 'linear' with type 'UnityEngine.Color'. Path 'skyColor'.
    Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CheckForCircularReference (Newtonsoft.Json.JsonWriter writer, System.Object value, Newtonsoft.Json.Serialization.JsonProperty property, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerProperty)
    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)
    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)

    When I set the type to Color32 it seems to work fine, so you may wish to clarify in the docs etc.

    cheers

    Nalin
     
  15. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    There is a converter for color in Newtonsoft.Json.Converters namespace. It should be mentioned in the docs but I'll double check. There are instructions for adding it to the default converters collection or adding it to your property via attribute. It's ColorConverter.
     
  16. puzzlekings

    puzzlekings

    Joined:
    Sep 6, 2012
    Posts:
    393
    I saw the docs for ColorConverter but was not sure of the syntax / steps, so a simple example would be great to see.
     
  17. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    Sure, start on on Page 10, there's a section on Serialization and Deserialization using converters.

    Code (csharp):
    1.  
    2. var settings = new JsonSerializerSettings();
    3. settings.Converters.Add(new ColorConverter());
    4. var json = JsonConvert.SerializeObject(colorObject, settings);
    5.  
    You could also do this somewhere in your code (only needs to happen once):
    Code (csharp):
    1.  
    2. JsonConvert.DefaultSettings().Converters.Add(new ColorConverter());
    3.  
    That would add the converter globally.

    Or you could add this to your color property:

    Code (csharp):
    1.  
    2. [JsonConverter(typeof(ColorConverter))]
    3.  
     
  18. puzzlekings

    puzzlekings

    Joined:
    Sep 6, 2012
    Posts:
    393
    Thank you so much!
     
    Dustin-Horne likes this.
  19. samoO

    samoO

    Joined:
    Nov 6, 2012
    Posts:
    2
    I included the new version from the Asset Store and I am trying to build for UWP, IL2CPP and Net 4.6 and get the following error:

    Code (CSharp):
    1. TypeLoadException: Could not load type 'Innoactive.Hub.SDK.JsonNetAccessTokenStore' from assembly 'Innoactive.Hub.Communication, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
    2. UnityEditor.Build.BuildPipelineInterfaces.InitializeBuildCallbacks (BuildCallbacks findFlags) (at C:/buildslave/unity/build/Editor/Mono/BuildPipeline/BuildPipelineInterfaces.cs:115)
    3. UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)
    Does anyone have an idea how to fix this or a hint in the right direction? Thank you!
     
  20. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    I don't quite fully support .NET 4.6 yet. Unity does not currently provide a way to map DLLs by .NET Version as well as platform and backend.

    That beign said, that error is not originating from JSON .NET. That looks like it's from whatever Innoactive.Hub.SDK is.. It's not able to load the Innoactive.Hub.Communication assembly. I have no idea what that is, but it's something else you have installed. It is possible though that it's failing to load because JSON .NET is not loading properly but It's hard to tell from that exception.
     
  21. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    I've attached an experimental version to support .NET 4.6 on UWP only (not other platforms yet). This package was exported from Unity 2017.
     

    Attached Files:

  22. samoO

    samoO

    Joined:
    Nov 6, 2012
    Posts:
    2
    Thank you for the reply!
    I found the problem and you are right, it has nothing to do with Json.NET. It was some weird linking issues.
     
    Dustin-Horne likes this.
  23. Jay-Pavlina

    Jay-Pavlina

    Joined:
    Feb 19, 2012
    Posts:
    195
    I'm using WebGL with .Net 4.6. I have the following error, and I'm not sure how to debug it. Any suggestions?
    ArgumentNullException: Value cannot be null.
    Parameter name: method
    at Newtonsoft.Json.Utilities.ValidationUtils.ArgumentNotNull (System.Object value, System.String parameterName) [0x00000] in <00000000000000000000000000000000>:0
    at Newtonsoft.Json.Utilities.LateBoundReflectionDelegateFactory.CreateParameterizedConstructor (System.Reflection.MethodBase method) [0x00000] in <00000000000000000000000000000000>:0
    at Newtonsoft.Json.Serialization.JsonArrayContract.CreateWrapper (System.Object list) [0x00000] in <00000000000000000000000000000000>:0
    at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateNewList (Newtonsoft.Json.JsonReader reader, Newtonsoft.Json.Serialization.JsonArrayContract contract, System.Boolean& createdFromNonDefaultCreator) [0x00000] in <00000000000000000000000000000000>:0
    at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateList (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, System.Object existingValue, System.String id) [0x00000] in <00000000000000000000000000000000>:0
    at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerMember, System.Object existingValue) [0x00000] in <00000000000000000000000000000000>:0
    at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.SetPropertyValue (Newtonsoft.Json.Serialization.JsonProperty property, Newtonsoft.Json.JsonConverter propertyConverter, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerProperty, Newtonsoft.Json.JsonReader reader, System.Object target) [0x00000] in <00000000000000000000000000000000>:0
    at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject (System.Object newObject, Newtonsoft.Json.JsonReader reader, Newtonsoft.Json.Serialization.JsonObjectContract contract, Newtonsoft.Json.Serialization.JsonProperty member, System.String id) [0x00000] in <00000000000000000000000000000000>:0
    at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Populate (Newtonsoft.Json.JsonReader reader, System.Object target) [0x00000] in <00000000000000000000000000000000>:0
    at Newtonsoft.Json.JsonSerializer.PopulateInternal (Newtonsoft.Json.JsonReader reader, System.Object target) [0x00000] in <00000000000000000000000000000000>:0
    at Newtonsoft.Json.JsonSerializer.Populate (Newtonsoft.Json.JsonReader reader, System.Object target) [0x00000] in <00000000000000000000000000000000>:0
    at Newtonsoft.Json.JsonConvert.PopulateObject (System.String value, System.Object target, Newtonsoft.Json.JsonSerializerSettings settings) [0x00000] in <00000000000000000000000000000000>:0
    at Newtonsoft.Json.JsonConvert.PopulateObject (System.String value, System.Object target) [0x00000] in <00000000000000000000000000000000>:0
    at ExplodingRabbit.TmxJson.TmxTileMap..ctor (System.String path, ExplodingRabbit.Unity.FileRetreivalType fileRetreivalType) [0x00000] in <00000000000000000000000000000000>:0
    at ExplodingRabbit.TmxImporter.TmxToTilemap.import () [0x00000] in <00000000000000000000000000000000>:0
    at ExplodingRabbit.TmxImporter.TmxToTilemap.Start () [0x00000] in <00000000000000000000000000000000>:0

    Edit: I was able to resolve the issue by changing all ILists to Lists. For some reason on WebGL, Json.Net was not able to populate ILists.
     
    Last edited: Nov 21, 2017
  24. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    You may occasionally run into this issue with List as well, moreso on iOS than webgl but it's because Unity sometimes strips a constructor off with il2cpp and the link.xml doesn't seem to be able to exclude all generic collections from stripping. Actually if you had a "new List<yourtype> somewhere in your code it would go back to working with IList.
     
  25. dadude123

    dadude123

    Joined:
    Feb 26, 2014
    Posts:
    790
    Hello,
    a few quick questions:

    - What version of the newtonsoft library is it based on nowadays?
    - Is there any performance comparison between this one and full-serializer? (serialization, deserialization, generated garbage)
    - There are some pretty old comments that things like Dictionary<ComplexType, ComplexType> is not handled well, is that still the case?

    Thanks!
     
  26. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    It is based on Json .Net 8.x and is a full port. One major difference between this and the SaladLabs version other than Json .net version is that I haven't removed any functionality (they removed bson support for instance). I don't have any performance comparisons but it's free so you could do one. I don't generally put much stock in those comparisons because it varies depending on what you're serializing.

    The functionality of complex types for dictionaries has not changed. This is because it would not produce valid json. You could easily serialize as List<KeyValuePair<ComplexType, Second type>> though.
     
    dadude123 likes this.
  27. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    Im not sure why this is the case. I have a feeling this is due to Unity stripping. It causes issues sometimes with generic collections in general because the link.xml doesn't honor those types. I've had one user submit a bug report for it.
     
  28. ehnree

    ehnree

    Joined:
    Dec 20, 2014
    Posts:
    7
    Hi Dustin,

    I'm having some trouble integrating JSON.NET into my Unity project. I am getting many errors of the flavor:

    "Assets/JsonDotNet/Source/Newtonsoft.Json/Converters/EnumerableVectorConverter.cs(36,48): error CS1644: Feature `null propagating operator' cannot be used because it is not part of the C# 4.0 language specification"

    The same is happening for 'dictionary initializer'. Most of these files are in the Newtonsoft folder.

    Sorry if this question has already been asked! Thanks for the help and releasing this awesome asset for free :)

    Best,
    ehnree
     
  29. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    Is this from the asset store or the GitHub repo? I need to get instructions up there if it's GitHub. The solution has to be compiled and the dlls put into the project and mapped. For now I'd suggest using the version from the asset store. it's exactly the same but the package imports dlls that are mapped for you.
     
  30. ehnree

    ehnree

    Joined:
    Dec 20, 2014
    Posts:
    7
    This is from the asset store. I'm importing the asset from the Unity asset store and I unzip the JsonDotNet201Source. Just tried reinstalling and got the same issue. I'm using Unity 5.6.2p2. :(
     
  31. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    Oh don't unzip the source. it's only there for reference. everything you need is already compiled and imported in the /assemblies folder.
     
  32. --Den--

    --Den--

    Joined:
    Sep 7, 2015
    Posts:
    6
    Does it work on Android with ill2cpp?
     
  33. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    Yes. It should work on all platforms with il2cpp. The only time issues are encountered is when Unity strips stuff it shouldn't like constructors on generic collections, but it's generally easy to mitigate if it happens.
     
  34. TooManySugar

    TooManySugar

    Joined:
    Aug 2, 2015
    Posts:
    864
    Hello.
    I'm trying to port my game to Windows store (8.1) as the game was developed using 4.7.2 and found that the binary formatter serialization is not available. I've spend quite an ammount of time trying to find a serialization solution but no way.

    I was trying Sharp Serializer but while seems to serialize with no errors when deserializing the dictionary that contains a custom class I get an error saying the default constructor is not defined, and that class has a single constructor. Error dissapears when I do add a blanc constructor but if I do so serialized data seems to be not read :\.

    What I need to serialize is a Dictionary<string,CustomClass> like data structure. The custom class being a holder of simple types like ints bools and an enum.

    With binary formatter I was using this serializable dictionary:
    https://forum.unity.com/threads/fin...acted-from-system-collections-generic.335797/

    With Sharp serializer it was giving errors so I moved everything to a regula runity dictionary and at that point Sharp Serializer requested the default constructor thing leading me to a dead end.

    So, would Json.net allow for serializing a dictionary wether is the serializable or the regular unity one with a custom class being the custom class the one attached below?.

    Thanks in advance.

    Code (CSharp):
    1. using UnityEngine;
    2. using System;
    3.  
    4. [Serializable]
    5. public enum  vehicleModel {
    6.  
    7.     //update 1.4-----------------------------------------
    8.     //Player
    9.     Player_T72,
    10.     Player_T80,
    11.     Player_T95,
    12.     Player_T14,
    13.     Player_Type10,
    14.     Player_Type90,
    15.  
    16.     //AI
    17.     AI_T72,
    18.     AI_T80,
    19.     AI_T95,
    20.     AI_T14,
    21.     AI_Type10,
    22.     AI_Type90,
    23.     //--------------------------------------------------
    24.  
    25.     //update 1.5
    26.     //Player
    27.     Player_SA_19,
    28.     Player_BMD3,
    29.     Player_BTR_80a,
    30.     Player_T34,
    31.     Player_T35,
    32.     Player_KV_1,
    33.     Player_KV_2,
    34.  
    35.     Player_Type87_AA,
    36.     Player_Type89,
    37.  
    38.     Player_Cromwell,
    39.     Player_Chieftain,
    40.     Player_Challenger_2,
    41.  
    42.     Player_M1A,
    43.     Player_Stryker,
    44.     Player_Sherman,
    45.  
    46.     Player_PanzerII,
    47.     Player_PanzerIV,
    48.     Player_TigerI,
    49.     Player_TigerII,
    50.     Player_Jagdtiger,
    51.     Player_Maus,
    52.     Player_Karl,
    53.  
    54.     //AI
    55.  
    56.     AI_SA_19,
    57.     AI_BMD3,
    58.     AI_BTR_80a,
    59.     AI_T34,
    60.     AI_T35,
    61.     AI_KV_1,
    62.     AI_KV_2,
    63.    
    64.     AI_Type87_AA,
    65.     AI_Type89,
    66.    
    67.     AI_Cromwell,
    68.     AI_Chieftain,
    69.     AI_Challenger_2,
    70.    
    71.     AI_M1A,
    72.     AI_Stryker,
    73.     AI_Sherman,
    74.    
    75.     AI_PanzerII,
    76.     AI_PanzerIV,
    77.     AI_TigerI,
    78.     AI_TigerII,
    79.     AI_Jagdtiger,
    80.     AI_Maus,
    81.     AI_Karl,
    82.  
    83.     //---------------------------
    84.     //Update1.6/
    85.     Player_ZTZ99,
    86.     Player_MCV,
    87.  
    88.     AI_ZTZ99,
    89.     AI_MCV,
    90.  
    91. }
    92.  
    93.  
    94. [Serializable]
    95. public class TankProperties   {
    96.  
    97.     public bool isPlayer;
    98.     public int team;
    99.     public int faction;
    100.     public int  vehicleType;
    101.     //public string model;
    102.     public vehicleModel model;
    103.     public int tier;
    104.     public int skin;
    105.     public int count;
    106.     public int era;
    107.  
    108.     public  TankProperties  (bool _isPlayer, int _team, int _faction,int  _vehicleType, vehicleModel _model, int _tier , int _skin, int _count, int _era)
    109.  
    110.     {
    111.         isPlayer     =     _isPlayer;
    112.         team         =    _team;
    113.         faction     =     _faction;
    114.         vehicleType =     _vehicleType;
    115.         model         =    _model;
    116.         tier         =     _tier;
    117.         skin         =    _skin;
    118.         count         =    _count;
    119.         era            =   _era;
    120.     }
    121.  
    122. }
    123.  
    124.  
    125.  
     
  35. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    I don't see why not, though you wouldn't need the Unity serializable wrapper for it with JSON .NET. It'll serialize dictionaries just fine. If you are keeping the wrapper for Unity purposes it should still work, but if there were hiccups it would be really easy to use a custom JsonConverter to handle it.
     
  36. TooManySugar

    TooManySugar

    Joined:
    Aug 2, 2015
    Posts:
    864
    Awesome!. I'll strip the [serializable] as Its a port of a finished game I won´t keep developing I did strip all teh stuff like the steamworks.net and such and converted into a win store specific Project. In my next Project I'll from start think of having multiple platforms and pay mor attention to theese things.

    If I manage to get it working in editor I may post again because the store text says
    "indows 8.1 is supported for 8.1 Universal on Unity 5 and above. If you have a special need for Windows 8.0, or Windows Phone 8.0/8.1 contact me and I can work on a special build"

    As I'm using 4.7.2 and targeting Windows 8.1 Universal to be used in desktop computers I understand there is the need for some specific build.
     
  37. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    Yeah it's a pain in the butt. It's because Unity 5 supports mapping of dlls to target platforms while 4.x does it.
     
  38. TooManySugar

    TooManySugar

    Joined:
    Aug 2, 2015
    Posts:
    864
    Hi.
    I managed to serialize but I'm getting an error when deserializing.
    Code (CSharp):
    1. JsonSerializationException: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.Dictionary`2[System.String,TankProperties]' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
    2. To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
    3. Path ''.
    4. Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureArrayContract (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract)
    5. Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateList (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, System.Object existingValue, System.String id)
    6. Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerMember, System.Object existingValue)
    7. Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType, Boolean checkAdditionalContent)
    At first I thought was because I was using the SerializableDictionary class but with built in dictionaries I get the same error.

    This is how I try to deserialize:

    Code (CSharp):
    1.     public static Dictionary<string,TankProperties> Load() {    
    2.         Debug.Log (Application.persistentDataPath + "/AI.dat");
    3.  
    4.         Dictionary<string,TankProperties> data;
    5.  
    6.         if(File.Exists(Application.persistentDataPath + "/AI.dat")) {
    7.             FileStream file = File.Open(Application.persistentDataPath + "/AI.dat", FileMode.Open);
    8.  
    9.             var reader = new BsonReader(file);
    10.             reader.ReadRootValueAsArray=true;
    11.  
    12.             var serializer = new JsonSerializer();
    13.             data = (Dictionary<string,TankProperties>) serializer.Deserialize < Dictionary < string,TankProperties>>(reader);
    14.  
    15.             file.Close();  
    16.         }
    17.         else{
    18.             data = new Dictionary<string,TankProperties>();
    19.         }
    20.  
    21.         Debug.Log ("dic lenght"+ data.Count);
    22.  
    23.  
    24.         return data;
    25. }
     
  39. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    that's odd... are you deserializing the same string you serialized?
     
  40. TooManySugar

    TooManySugar

    Joined:
    Aug 2, 2015
    Posts:
    864
    Yes, I thought of that too, I did delete the serialized file just in case.

    Got to say that when installing the JsonDotNet only AOT shows under Asemblies folder. No Windows or Standalone folder and Mono develop would only get the dll when placed under Plugins not when Plugins/Metro. Just in case this can be a clue.

    I also just tried IDictionary instead of unity Dictionary with same error.
     
  41. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    Yeah, you're on 4.x so there is only an AOT dll. Is the error happening in the editor or only in the finished build?
     
  42. TooManySugar

    TooManySugar

    Joined:
    Aug 2, 2015
    Posts:
    864
    whait, I think I fixed!
     
  43. TooManySugar

    TooManySugar

    Joined:
    Aug 2, 2015
    Posts:
    864
    damm, its working!!
    I thought that with collections I had to set the reader as this:
    reader.ReadRootValueAsArray=true;
    but commenting the line made it work! yay!!

    I noticed data is written much slower into regular dicitonary tan teh one I was using so I'll try with the serializable dictionary too. If not, is not that much of an issue is just menú going bit slower!

    OMG, I thought during theese last days that the port was not gonna happen I'm starting to see the light now !
     
    Dustin-Horne likes this.
  44. TooManySugar

    TooManySugar

    Joined:
    Aug 2, 2015
    Posts:
    864
    It was only editor. Today I was able to make the first build because till today Project was full of stuff not compatible with the build . I don´t even know jet how to run the Windows store build as there are a bunch of files and no one seemed executable XD
     
  45. TooManySugar

    TooManySugar

    Joined:
    Aug 2, 2015
    Posts:
    864
    Hello again. I'm totally stuck in the mud. Deep in the mud.

    The in editor serialization/deserialization is working.

    But the WSA code keeps trowing exceptions when trying to compile.

    I use mono develop so the .NET code is not debuged realtime so I find all this stuff when building.

    Fortunatelly the serialization thing is the last one pending because without the serialization code I can make a build.

    The thig is that .NET is missing a number of namespaces or extensions so no more file.exists , filestream , write /read file restrictions etc...

    I've been finding this out theese days.
    Interesting linke for anyone in similar situation:
    https://docs.microsoft.com/en-us/windows/uwp/gaming/missing-dot-net-apis-in-unity-and-uwp

    At this point what is driving me mad is the file creation, checking if existing, Reading procedures.
    Aparently the way to go is using the "
    using System.Threading.Tasks;" namespace and usint "tasks" wich I understand is a similar to C#functions but seem to return the values in a different way.

    For instnace, for loading the serialize data <string,object> Dictionary I've a method that has different paths for standalone and WinStore:
    Code (CSharp):
    1. public static Dictionary<string,TankProperties> Load() {
    2.  
    3.         bool dataFile=false;
    4.         Dictionary<string,TankProperties> data;
    5.  
    6.         #if !NETFX_CORE
    7.         //code active when building for platforms other than WSA
    8.         Debug.Log (Application.persistentDataPath + "/AI.dat");
    9.  
    10.         FileStream file = null;
    11.      
    12.         if(File.Exists(Application.persistentDataPath + "/AI.dat")) {
    13.             dataFile=true;
    14.             file = File.Open(Application.persistentDataPath + "/AI.dat", FileMode.Open);
    15.         }
    16.  
    17.         #else
    18.         Stream file;
    19.         //if(DoesFileExist()==true){
    20.             file = (Stream) SaveLoad_TankData._SVL.LoadFileWSA();
    21.             dataFile=true;
    22.         //}
    23.         #endif
    24.  
    25.         //DESERIALIZE
    26.         if (dataFile) {
    27.             var reader = new BsonReader (file);
    28.             //reader.ReadRootValueAsArray=true;
    29.          
    30.             var serializer = new JsonSerializer ();
    31.             data = (Dictionary<string,TankProperties>)serializer.Deserialize < Dictionary < string,TankProperties>> (reader);
    32.          
    33.             #if !NETFX_CORE
    34.             file.Close ();
    35.             #else
    36.             file.Dispose();
    37.             #endif
    38.             Debug.Log ("dic lenght" + data.Count);
    39.         }
    40.         else {
    41.             data = new Dictionary<string,TankProperties>();
    42.         }    
    43.  
    44.         return data;
    45.     }
    46.  
    With the code as it is, being the class statig now It is giving me errors because I cant declare instance members in an static class. I do non static and I reference itself with

    Code (CSharp):
    1. public static SaveLoadTankData _SVL;
    2. public void Start(){
    3. _SVL=this;
    4. }
    5.  
    after re-routing all the related scripts the issue I get is that when attemping to read calling the task as follow:

    Code (CSharp):
    1. Stream file;
    2.         //if(DoesFileExist()==true){
    3.             file = (Stream) SaveLoad_TankData._SVL.LoadFileWSA();
    4.             dataFile=true;
    5.         //}
    I get an error saying something like that I can convert System.Threading.Tasks.IO.Stream to System.IO.Stream;

    even if I tryed with the task returning an string and assiging to a string variable get same error with the string type in the warning.

    This is the Windows store part that is there to substitute the lacking features of System.IO
    Code (CSharp):
    1. #if NETFX_CORE
    2.  
    3.     //SAVE-------------------------------------------
    4.  
    5.     public async Task SaveFileWSA(Dictionary<string,TankProperties> TankDictionary)
    6.     {
    7.         // create a file with the given filename in the local folder; replace any existing file with the same name
    8.         StorageFile file = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("AI.dat", CreationCollisionOption.ReplaceExisting);
    9.        
    10.         // write  into the file
    11.         using (var stream = await file.OpenStreamForWriteAsync())
    12.         {
    13.             var writer = new BsonWriter (stream);
    14.             var serializer = new JsonSerializer ();
    15.             serializer.Serialize (writer, TankDictionary);
    16.         }
    17.     }
    18.    
    19.  
    20.     // CHECKFILEXISTS--------------------------------
    21.     static async Task<bool> DoesFileExist()
    22.     {
    23.         try
    24.         {
    25.             await ApplicationData.Current.LocalFolder.GetFileAsync("AI.dat");
    26.             return true;
    27.         }
    28.         catch
    29.         {
    30.             return false;
    31.         }
    32.     }
    33.    
    34.    
    35.     //    LOAD--------------------------------
    36.    
    37.     public async Task<Stream> LoadFileWSA()
    38.     {
    39.         // access the local folder
    40.         StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
    41.  
    42.         // open the file  for reading
    43.         Stream stream = await local.OpenStreamForReadAsync("AI.dat");
    44.  
    45.         /*
    46.         String dic;
    47.        
    48.         // copy the file contents into the dictionary 'dic'
    49.         using (StreamReader reader = new StreamReader(stream))
    50.         {
    51.             dic = reader.ReadToEnd();
    52.         }
    53.         */
    54.        
    55.         return stream;
    56.     }
    57.     #endif
    I would please beg for some help to help me read, check if file exists and feed the serializer with the data in the #NETFX_CORE part of the code as it feels as if the tasks and regular methods couldnt comunícate as it is now.
     
  46. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    That particular setting is for supporting top level arrays with BSON.

    My email address is in the included Readme / documentation, or you can contact me at https://www.dustinhorne.com/contact

    Drop me an email and I'll work on seeing if I can get you something that works with WSA. I can't do DLL mapping in 4.x but if you're only worried about WSA, we can do it through /plugins folders by putting the current AOT build in a /Editor folder and putting a WSA build in a /Plugins folder.
     
    TooManySugar likes this.
  47. mihakinova

    mihakinova

    Joined:
    Jan 6, 2015
    Posts:
    85
    I've searched through this thread and still couldn't find a solution that worked for me so here goes...

    I'm getting the same issue as some other people here, with IL2CPP, IList and iOS.

    Getting this error when deserializing:

    [Exception] ArgumentNullException: Argument cannot be null.
    Parameter name: method
    Newtonsoft.Json.Utilities.LateBoundReflectionDelegateFactory..ctor ()
    Newtonsoft.Json.Utilities.LateBoundReflectionDelegateFactory.CreateParameterizedConstructor (System.Reflection.MethodBase method)
    Newtonsoft.Json.Serialization.JsonArrayContract.CreateWrapper (System.Object list)
    Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateNewList (Newtonsoft.Json.JsonReader reader, Newtonsoft.Json.Serialization.JsonArrayContract contract, Boolean& createdFromNonDefaultCreator)
    Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateList (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, System.Object existingValue, System.String id)
    Newtonsoft.Json.Serialization.JsonSerializerInternalReader.SetPropertyValue (Newtonsoft.Json.Serialization.JsonProperty property, Newtonsoft.Json.JsonConverter propertyConverter, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerProperty, Newtonsoft.Json.JsonReader reader, System.Object target)
    Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject (System.Object newObject, Newtonsoft.Json.JsonReader reader, Newtonsoft.Json.Serialization.JsonObjectContract contract, Newtonsoft.Json.Serialization.JsonProperty member, System.String id)
    Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject (Newtonsoft.Json.JsonReader reader, System.Type objectType, Newtonsoft.Json.Serialization.JsonContract contract, Newtonsoft.Json.Serialization.JsonProperty member, Newtonsoft.Json.Serialization.JsonContainerContract containerContract, Newtonsoft.Json.Serialization.JsonProperty containerMember, System.Object existingValue)
    Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType, Boolean checkAdditionalContent)
    Newtonsoft.Json.JsonSerializer.DeserializeInternal (Newtonsoft.Json.JsonReader reader, System.Type objectType)
    Newtonsoft.Json.JsonConvert.DeserializeObject (System.String value, System.Type type, Newtonsoft.Json.JsonSerializerSettings settings)
    Newtonsoft.Json.JsonConvert.DeserializeObject[T] (System.String value, Newtonsoft.Json.JsonSerializerSettings settings)

    The class that i'm trying to deserialize looks something like this (ZeroFormattable and Index probably don't matter, just including them for completeness):

    Code (CSharp):
    1. [ZeroFormattable]
    2. public class User
    3. {
    4.     [Index(0)]
    5.     public virtual string firstName { get; set; }
    6.     [Index(1)]
    7.     public virtual string lastName { get; set; }
    8.     [Index(2)]
    9.     public virtual IList<string> family { get; set; }
    10.     [Index(3)]
    11.     public virtual IList<string> friends { get; set; }
    12. }
    I tried including this in my project but it didn't work. Not sure where to go from here... thoughts?
     
  48. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    Change IList<string> to List<string> and see if that will fix it. If not I can give you a workaround.
     
  49. mihakinova

    mihakinova

    Joined:
    Jan 6, 2015
    Posts:
    85
    That does fix it, but I would like to use IList (ZeroFormatter needs it to take full advantage of it's lazy deserialization). A workaround where I can keep IList would be awesome, if possible.
     
  50. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    Some where esle in your code, only has to executed once, add something like:
    var x = new List<string>(); which will prevent if from. being stripped.
     
unityunity