Search Unity

  1. Click here to see what's on sale for the "Best of Super Sale" on the Asset Store
    Dismiss Notice
  2. 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
    Now that 2017 is released I'll start working on a .NET 4.x support version so it'll support the expanded types like BigInteger. I'm hoping to have an initial release ready in the next couple of weeks. The current version works with .NET 4.6 but doesn't support the extra types. It will be considered Beta as long as 4.6 support in Unity is still marked Experimental because I'm not sure what changes and/or bugs they may still have.
     
    jGate99 likes this.
  2. jGate99

    jGate99

    Joined:
    Oct 22, 2013
    Posts:
    1,211
    waiting
     
  3. anton_breusov

    anton_breusov

    Joined:
    Oct 10, 2015
    Posts:
    4
    Hi!

    Please check this issue and proposed workaround (until Unity team adresses it on their side): https://forum.unity3d.com/threads/u...monoproperty-getteradapt.332335/#post-3153825
     
  4. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    Thanks for the update. This issue had not yet been reported. I'll have to look at it a little more in depth. BindingFlags.Default is not appropriate for my use case because I have to be able to support private member serialization and deserialization as well.
     
  5. layola

    layola

    Joined:
    Aug 6, 2013
    Posts:
    94
    hi,Dustin-Horne,How to use JsonConvert.SerializeObject TonemappingColorGrading and DeserializeObject it ?
    any idea?
     
  6. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    I'd have to look at it... that class is included as part of Standard Assets right?
     
  7. layola

    layola

    Joined:
    Aug 6, 2013
    Posts:
    94
    yes,you can find it on Assetsstore ,

    when I try to use

    var ouput = JsonConvert.SerializeObject(gameObject.GetComponent<TonemappingColorGrading>());

    -----------------------------------------------

    JsonSerializationException: Self referencing loop detected for type 'UnityStandardAssets.CinematicEffects.TonemappingColorGrading'.
    Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CheckForCircularReference (System.Object value, Nullable`1 referenceLoopHandling, Newtonsoft.Json.Serialization.JsonContract contract) (at Assets/thirdPart/JsonDotNet/Source/Serialization/JsonSerializerInternalWriter.cs:238)
    Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.WriteMemberInfoProperty (Newtonsoft.Json.JsonWriter writer, System.Object memberValue, Newtonsoft.Json.Serialization.JsonProperty property, Newtonsoft.Json.Serialization.JsonContract contract) (at Assets/thirdPart/JsonDotNet/Source/Serialization/JsonSerializerInternalWriter.cs:215)
    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.JsonContract collectionValueContract) (at Assets/thirdPart/JsonDotNet/Source/Serialization/JsonSerializerInternalWriter.cs:341)
     
  8. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    Yep, it has a property which returns either itself or another ToneMappingColorGrading object. I have to write a custom converters for it. Or, you can do JsonConvert.DefaultSettings().ReferenceLoopHandling = ReferenceLoopHandling.Ignore.
     
  9. javierfed

    javierfed

    Joined:
    Apr 10, 2015
    Posts:
    25
    I have tried the suggestions in posts:
    https://forum.unity3d.com/threads/json-net-for-unity.200336/page-28#post-2893716
    and
    https://forum.unity3d.com/threads/json-net-for-unity.200336/page-28#post-2910881

    but I am still getting this same error... it's identical except I am using longs instead of singles.
    I have the fix in the link.xml and the hack call to exception

    Code (CSharp):
    1. PhonePlayer(*****):56000</i> ExecutionEngineException: Attempting to call method 'System.Collections.Generic.List`1[[System.Int64, mscorlib, Version=2.0.0.0, Culture=, PublicKeyToken=b77a5c561934e089]]::.ctor' for which no ahead of time (AOT) code was generated.
    2.   at System.Reflection.MonoCMethod.InternalInvoke (System.Object obj, System.Object[] parameters, System.Exception& exc) [0x00000] in <filename unknown>:0
    I am tearing my hair out trying to get this fixed. it only happens when pushed to an IOS device. for everything else this plugin works perfectly...

    we are running in the newest version of unity... the 2017.1.0f3 version
     
    Last edited: Aug 5, 2017
  10. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    Sent you a PM. We'll work on figuring it out and in the meantime write you a custom JsonConverter to get you up and running.
     
  11. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    If anyone else is running into this issue, PM me and I'll share a custom converter that will be included in future updates.
     
  12. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    I will be pushing an update this week. I found a branch of code that wasn't AOT safe and modified it. It's currently being tested. It affects a small but not insignificant number of people and doesn't always cause an issue. But, if anyone is running into the MonoProperty :: GetAdapterFrame issue when serializing with il2cpp this should fix it.
     
  13. adamt

    adamt

    Joined:
    Apr 1, 2014
    Posts:
    116
    It looks like version 10.0 of Json.NET added back the async functionality. Do you have any plans to integrate it into your plugin?

    We download tuning/configuration data from our server on application start as well as whenever a client device comes back from suspension (our game runs on iOS and Android). While this data isn't as big as some of the other commenters in this thread, it is larger than a couple of MB and there's a considerable hitch when we deserialize the data on the main thread.

    If I could amortize the cost of deserializing the data over the course of a few frames using coroutines, that would be nice. If not, though, I can look into using a worker thread instead for cases where the incoming data is not insignificant. Just wanted to get your thoughts on the situation.

    For reference, here's how we're currently handling the deserialization:

    Code (CSharp):
    1. private void HandleSuccessfulResponse<T>(UnityWebRequest request, ResponseDelegate<T> callback)
    2. {
    3.     string responseString = request.downloadHandler.text;
    4.  
    5.     try
    6.     {
    7.         Dictionary<string, JToken> response = JsonConvert.DeserializeObject<Dictionary<string, JToken>>(responseString);
    8.  
    9.         T result = response["data"].ToObject<T>();
    10.  
    11.         if(callback != null)
    12.         {
    13.             callback(result);
    14.         }
    15.     }
    16.     catch(JsonReaderException e)
    17.     {
    18.         Debug.LogErrorFormat("Error reading REST API response data. Possibly malformed data. URL: {0}, Data: {1}", request.url, e.Message);
    19.  
    20.         UIManager.Instance.ShowAlert("Client Error", "An error occurred while reading data from the server. The team has been notified.");
    21.     }
    22. }
    23.  
     
  14. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    Ill take a look at what was added back but there's nothing stopping you from doing it in a separate thread or in a coroutine now.
     
  15. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    Just an update on where I'm heading with this... I'm considering skipping 9.0 and going to 10.0 but there are some issues. There are some things that have been deprecated. BSON support has been removed from the 10.0 package and moved to a separate package available on NuGet. I have a considerable number of customers using BSON so I don't want to just deprecate a feature. I have to look at what it will take to keep it in. There are some other things that have been deprecated as well so I have to make sure they won't have a significant impact on existing user base.

    However, there are some significant performance improvements in 10.0. In general terms they are minor, but they have a larger impact on Unity users because they will improve performance and garbage generation when serializing and deserializing structs.

    That being said, the async support that's built into Json .NET 10 also relies on async/await which isn't widely available for Unity yet and not at all for 5.x users. WebGL also doesn't support async so the addition of the async methods itself isn't compelling enough to upgrade. I'll have to see what it will take to do the upgrade without losing core functionality.
     
    Tinjaw likes this.
  16. adamt

    adamt

    Joined:
    Apr 1, 2014
    Posts:
    116
    Thanks for the update, Dustin.

    I'm going to be looking into offloading the deserialization of the object onto a separate thread. However, you mention there's nothing stopping me from using a coroutine. I was under the impression that JsonConvert.DeserializeObject is a blocking call, so there's no real way for me to yield and check if it's finished its work. Is there something I'm missing?
     
  17. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    I see what you're saying there. Inside your co-routine you'd need to create a bool to know when it's done, so something like this:

    Code (csharp):
    1.  
    2. bool isComplete = false;
    3.  
    4. var t1 = new Thread(() => {
    5.     JsonConvert.DeserializeObject<YourObject>(yourJson);
    6.     isComplete = true;
    7. });
    8.  
    9. t1.Start();
    10.  
    11.  
     
  18. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    Obviously you want some error checking, etc. in there as well so you don't get a stuck state that never completes.
     
  19. adamt

    adamt

    Joined:
    Apr 1, 2014
    Posts:
    116
    Aah, got it.

    I was thinking you were talking about an either/or situation (i.e., either 1.) using a separate thread with something like a queue in my MonoBehaviour's Update method to check when the work is done, or 2.) strictly a coroutine wrapping the deserialization). Effectively I guess option 1 in my scenario is almost the same as thread + coroutine anyway, and option 2 probably wouldn't really work without creating a custom, streaming deserializer.

    Thanks again for your replies!
     
  20. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    Yep, sorry for the confusion. Meant that you can just use threading in your own way or within the context of a co-routine so you can yield and essentially progress update. :) So if you want to do some animation, etc while it loads. With that much json though... huge amount of objects, there will likely be some GC cycles so beware of that.
     
  21. adamt

    adamt

    Joined:
    Apr 1, 2014
    Posts:
    116
    Yeah, fortunately it doesn't happen often. We do have smaller events that call our REST API and deserialize responses littered throughout our app, but fortunately the payload is generally between 0.1 - 1 KB. Still, there can be a hitch and I'm looking at ways to mitigate them -- especially when you're in the middle of a battle -- as much as possible.
     
    Dustin-Horne likes this.
  22. kokteylgaming

    kokteylgaming

    Joined:
    Nov 2, 2016
    Posts:
    7
    Hello,

    I am having this problem while trying to run on iOS device.

    MissingMethodException: Method not found: 'Default constructor not found...ctor() of System.ComponentModel.TypeConverter'.

    at System.Activator.CreateInstance (System.Type type, Boolean nonPublic) [0x00000] in <filename unknown>:0

    at System.ComponentModel.TypeDescriptor.GetConverter (System.Type type) [0x00000] in <filename unknown>:0

    at Newtonsoft.Json.Serialization.DefaultContractResolver.CanConvertToString (System.Type type) [0x00000] in <filename unknown>:0

    at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateContract (System.Type objectType) [0x00000] in <filename unknown>:0

    at Newtonsoft.Json.Serialization.DefaultContractResolver.ResolveContract (System.Type type) [0x00000] in <filename unknown>:0

    at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType, Boolean checkAdditionalContent) [0x00000] in <filename unknown>:0

    at Newtonsoft.Json.JsonSerializer.DeserializeInternal (Newtonsoft.Json.JsonReader reader, System.Type objectType) [0x00000] in <filename unknown>:0

    at Newtonsoft.Json.JsonConvert.DeserializeObject (System.String value, System.Type type, Newtonsoft.Json.JsonSerializerSettings settings) [0x00000] in <filename unknown>:0

    at Newtonsoft.Json.JsonConvert.DeserializeObject[T] (System.String value, Newtonsoft.Json.JsonSerializerSettings settings) [0x00000] in <filename unknown>:0

    at CoreManagers.UserManager.LoadUserData () [0x00000] in <filename unknown>:0


    with these build settings



    I've already added link.xml to my project as;

    Code (CSharp):
    1. <linker>
    2.     <assembly fullname="System">
    3.         <type fullname="System.ComponentModel.TypeDescriptor" preserve="all"/>
    4.         <type fullname="System.ComponentModel.TypeConverter" preserve="all"/>
    5.         <type fullname="System.ComponentModel.ArrayConverter" preserve="all"/>
    6.         <type fullname="System.ComponentModel.BaseNumberConverter" preserve="all"/>
    7.         <type fullname="System.ComponentModel.BooleanConverter" preserve="all"/>
    8.         <type fullname="System.ComponentModel.ByteConverter" preserve="all"/>
    9.         <type fullname="System.ComponentModel.CharConverter" preserve="all"/>
    10.         <type fullname="System.ComponentModel.CollectionConverter" preserve="all"/>
    11.         <type fullname="System.ComponentModel.ComponentConverter" preserve="all"/>
    12.         <type fullname="System.ComponentModel.CultureInfoConverter" preserve="all"/>
    13.         <type fullname="System.ComponentModel.DateTimeConverter" preserve="all"/>
    14.         <type fullname="System.ComponentModel.DecimalConverter" preserve="all"/>
    15.         <type fullname="System.ComponentModel.DoubleConverter" preserve="all"/>
    16.         <type fullname="System.ComponentModel.EnumConverter" preserve="all"/>
    17.         <type fullname="System.ComponentModel.ExpandableObjectConverter" preserve="all"/>
    18.         <type fullname="System.ComponentModel.Int16Converter" preserve="all"/>
    19.         <type fullname="System.ComponentModel.Int32Converter" preserve="all"/>
    20.         <type fullname="System.ComponentModel.Int64Converter" preserve="all"/>
    21.         <type fullname="System.ComponentModel.NullableConverter" preserve="all"/>
    22.         <type fullname="System.ComponentModel.SByteConverter" preserve="all"/>
    23.         <type fullname="System.ComponentModel.SingleConverter" preserve="all"/>
    24.         <type fullname="System.ComponentModel.StringConverter" preserve="all"/>
    25.         <type fullname="System.ComponentModel.TimeSpanConverter" preserve="all"/>
    26.         <type fullname="System.ComponentModel.UInt16Converter" preserve="all"/>
    27.         <type fullname="System.ComponentModel.UInt32Converter" preserve="all"/>
    28.         <type fullname="System.ComponentModel.UInt64Converter" preserve="all"/>
    29.     </assembly>
    30. </linker>
    31.  

    Which part I am doing wrong? Please help me, thank you so much!
     
  23. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    Drop me an email and I'll send you an updated link.xml file. I don't see anything wrong off hand there... but it looks like Unity is still stripping Type converter for you.
     
  24. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    Json .NET For Unity has been included in the back to school sale on the asset store. Get it while it's 40% off!
     
  25. dtaTrifork

    dtaTrifork

    Joined:
    Aug 21, 2017
    Posts:
    3
    Will there be an update including the newtonsoft.json.schema namespace, or a separate asset for this at some time?
     
  26. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    No. JNK made json schema obsolete in Json .Net and made it a separate product. It is a commercial product so the only one who could port it would be him unfortunately.

    https://www.newtonsoft.com/jsonschema
     
  27. gcqinging

    gcqinging

    Joined:
    Nov 10, 2014
    Posts:
    2
    I got this error

    ExecutionEngineException: Attempting to call method 'System.Collections.Generic.List`1[[UnityEngine.Keyframe, UnityEngine, Version=0.0.0.0, Culture=, PublicKeyToken=null]]::.cctor' for which no ahead of time (AOT) code was generated.

    at System.Reflection.MonoCMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000] in <filename unknown>:0

    at Newtonsoft.Json.Utilities.LateBoundReflectionDelegateFactory+<>c__DisplayClass5_0`1[T].<CreateDefaultConstructor>b__1 () [0x00000] in <filename unknown>:0

    at Newtonsoft.Json.Serialization.JsonArrayContract.CreateTemporaryCollection () [0x00000] in <filename unknown>:0

    at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateNewList (Newtonsoft.Json.JsonReader reader, Newtonsoft.Json.Serialization.JsonArrayContract contract, Boolean& createdFromNonDefaultCreator) [0x00000] in <filename unknown>: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 <filename unknown>: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 <filename unknown>:0
     
  28. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    Can you send me an email: Dustin(a)ParentElement.com and I'll send you an updated link.xml file and one other change. Unit is stripping the generic list constructor.
     
  29. DavidBVal

    DavidBVal

    Joined:
    Mar 13, 2017
    Posts:
    132
    Hello, as a newcomer to Unity (I come from Java and LibGDX) I was surprised to find out that the native JSON support does not serialize correctly Dictionaries and Arrays, and ignores private fields as well.

    I'm building a pretty complex game and saving/loading will need to serialize rather large data structures including nested arrays, all kind of lists, etc. and of course loading the json string directly into an object. All of this was trivial with my previous language and libraries; will JSON.NET provide me this functionality I was taking for granted? Are there any limitations of this library I should be aware of?
     
  30. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    Hey David, thanks for your interest. Yes it does and I got and replied to your email as well.
     
  31. odysoftware

    odysoftware

    Joined:
    Jul 21, 2015
    Posts:
    60
    Hey there, its my first time I am building for iOS... so I was hoping everything is working as with Android/Windows - but it didn't :)

    The problem is I have no idea what I am doing wrong. I have a custom .NET 3.5 game library dll which is also linking to your Json.NET library from Unity and I am calling PopulateObject from there - this will then be called from a Unity object and it always results in the following error:

    JsonSerializationException: Unable to find a constructor to use for type dummy.GameData.BaseClass. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute. Path 'dummyList[0]._id', line 4, position 12.
    at AlphaControl+<AlphaAnim>c__Iterator0.Reset () [0x00000] in <filename unknown>:0
    at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateNewObject (Newtonsoft.Json.JsonReader reader, Newtonsoft.Json.Serialization.JsonObjectContract objectContract, Newtonsoft.Json.Serialization.JsonProperty containerMember, Newtonsoft.Json.Serialization.JsonProperty containerProperty, System.String id, Boolean& createdFromNonDefaultCreator) [0x00000] in <filename unknown>:0
    ......

    In Android and Windows I never needed a constructor and everything is working as it should - I guess it was populated via the fields/properties itself.

    However just for testing purposes I added now a new empty constructor and marked it also with [JsonConstructor], just to be sure. But the same exception still occurs?

    Do you have an idea why this happens? Do I require for AOT iOS a complete constructor with all the arguments (using default options from json) ?

    Or do I have a problem because I am not directly calling Json.NET from within Unity, but with my external unity compatible .NET dll (there I have a reference to your json.net library - standalone from the asset).

    Thanks a lot for your help,
    Oliver
     
    Last edited: Oct 2, 2017
  32. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    I'd have to see some actual example code to know for sure... It's probably not your primary object that's causing hte issue. I'm not sure what "dummyList[0]._id" is... it looks to me like there's a different object it's trying to construct and add as a property onto your object but it can't find a constructor for it. This is likely due to the IL2CPP compiler stripping something (constructors) off one ore more of your objects. Stripping is inconsistent between iOS, Android, etc.. .even when both platforms are using IL2CPP so it's not at all surprising for it to work for one and not another.
     
  33. odysoftware

    odysoftware

    Joined:
    Jul 21, 2015
    Posts:
    60
    Hey there - I guess I confused you because I have used dummy instead of original names:) But I can give you a direct exmaple:

    Code (Csharp):
    1.  
    2.  
    3. public class JsonDB
    4. {    
    5.         public List<BaseMonsterCard> MonsterCards { get { return monsterCards; } set { monsterCards = value; } }    
    6.         private List<BaseMonsterCard> monsterCards = new List<BaseMonsterCard>();
    7.  
    8.         public void LoadJson(string _json)
    9.         {
    10.             JsonConvert.PopulateObject(_json, this);
    11.         }
    12. }
    13.  
    14. public class BaseMonsterCard:BaseCard
    15. {                                  
    16.         public enum MonsterTypes
    17.         {
    18.             Normal = 1,
    19.             Elite = 2,
    20.             Boss = 3
    21.         }
    22.  
    23.         public int ID { get { return _id; } }
    24.         [JsonProperty]
    25.         private int _id = -1;
    26.  
    27.         public MonsterTypes MonsterType { get { return monsterType.ToEnum<MonsterTypes>(MonsterTypes.Normal); } }
    28.         [JsonProperty]
    29.         private string monsterType = "";
    30.  
    31.          ..................
    32. }
    33.  
    34.  
    So in the json File I have it like this:

    Code (JSON):
    1.  
    2. {
    3.   "monsterCards": [
    4.     {
    5.       "_id": 1,
    6.       "cardType": "MonsterCard",
    7.       ....
    8.     }]
    9. }
    10.  
    So in my eyes nothing special and that works fine in Android/Windows and gets parsed perfectly. It also doesn't require any constructor. But in iOS I get the Error I mentioned in the previous post, where dummy.GameData.BaseClass = BaseMonsterCard and the List is referring to: List<BaseMonsterCard>()

    Hope this helps?
     
    Last edited: Oct 2, 2017
  34. odysoftware

    odysoftware

    Joined:
    Jul 21, 2015
    Posts:
    60
    More observations... I think stripping cannot be the problem here - because I just tried to do a preserve="all" on the whole System Assembly as well as in my Custom Assembly.

    Now I wonder if the problem is related to how I use Json? Is the above example clear to you? Do I need a constructor - but in windows/android its working like this..... ?

    Or could be the reason that I am calling Json from a standard non unity .NET 3.5 Subset dll with just a reference to one of your Json.NET dlls from Unity. Since my DLL is compiling for all 3 Versions (iOS/Android/Windows), but your Json.NET is using 3 different dlls for each platform.... - but in the end it should automatically use the correct one depending on platform, since I am only using a reference to Json.NET...

    For me its strange that regardless what I change here (creating constructors etc.) it is always throwing this JsonSerializationException: Unable to find a constructor to use.... exception...

    Thanks a lot for your time,
    Oliver
     
  35. odysoftware

    odysoftware

    Joined:
    Jul 21, 2015
    Posts:
    60
    Okay I guess I did something wrong with the link.xml file. I just tried it again with a clean link.xml file and preserving my whole external dll. And now everything works fine... so yes it was indeed a stripping problem of custom assemblies - I guess it removed my Json Attributes.

    Thanks again,
    Oliver
     
  36. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    Sorry for the delay in response, but glad now you got it figured out. Yes, 99 times out of 100 when I get reports like this (which is just about all the reports I get), stripping is the issue. You shouldn't have to explicitly add a constructor, though it's a good idea, even if you just make it private and specify it as the constructor for Json .NET to use.

    One other note, if you run into a similar issue with the List<T>, let me know... there's an infuriating bug I haven't been able to find a way around yet (Unity bug). It sometimes strips constructors for List<T>, even with System.Collections.Generic set to preserve all.
     
  37. mdrotar

    mdrotar

    Joined:
    Aug 26, 2013
    Posts:
    377
    Is JSON.NET For Unity going to be updated? The asset store says it's based on 8.0.3 and the current version of Newtonsoft Json.NET is 10.0.3.
     
  38. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    It may at some point, but there are a couple of considerations currently. The new version actually removes support for some things customers are using (Bson stuff for example) so I cannot just upgrade as it may be a breaking change. Secondly, the newest official releases support .NET Core so I want to slow roll it and keep it in sync with Unity's frame work version upgrades and make sure I can support the upcoming package manager.
     
  39. kborod

    kborod

    Joined:
    Oct 19, 2017
    Posts:
    2
    Hi!
    Try to serialize the dictionary
    Code (CSharp):
    1. var myDict = new Dictionary<string, string>() { {"a","1"}, {"b","2"}  };
    2. Debug.Log(Newtonsoft.Json.JsonConvert.SerializeObject(myDict));
    and result is:
    [{"Key":"a","Value":"1"},{"Key":"b","Value":"2"}]​
    But I need the result in another format:
    { "a": "1", "b": "2"}​
    How can I do this?
    thanks in advance.
     
    Last edited: Oct 19, 2017
  40. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    Let me take a look... I thought by default it already used that format but I could be wrong... have you changed any of the default serializer settings?
     
  41. kborod

    kborod

    Joined:
    Oct 19, 2017
    Posts:
    2
    I apologize for my carelessness.. The problem is not with your asset.
     
    Dustin-Horne likes this.
  42. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    Not a problem at all. :) My guess is that it was actually somehow getting converted to a List<KeyValuePair<string, string>> rather than a Dictionary<string, string>.
     
  43. jGate99

    jGate99

    Joined:
    Oct 22, 2013
    Posts:
    1,211
    @Dustin-Horne Currently i use following code to deserialize
    PagingInfo = response["pagingInfo"].ToObject<VOPagingInfo>();

    However above code create a new VOPagingInfo each time, can i pass it existing instance when deserialziing?
    something like response["pagingInfo"].ToObject<VOPagingInfo>(PagingInfo);

    Please advise
     
  44. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    Yes, when I get to my office I can give you a full example,but there's a PopulateObject call you can use instead.
     
    jGate99 likes this.
  45. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    Sorry for the delay.. So there are a couple of ways to do this. JsonConvert has a PopulateObject method on it... JObject does not. You can accomplish it using a JsonSerializer and JsonReader though. So, given your response, here is hte simplest method:
    Code (csharp):
    1.  
    2. //Get the json that represents the pagingInfo property
    3. var json = response["pagingInfo"].ToString();
    4.  
    5. //Populate an existing PagingInfo object
    6. JsonConvert.PopulateObject(json, PagingInfo);
    7.  
    The second way is by using a reader and serializer directly:
    Code (csharp):
    1.  
    2. var reader = response["pagingInfo"].CreateReader();
    3. var serializer = new JsonSerializer();
    4. serializer.Populate(reader, PagingInfo);
    5.  
    Either/or should work just as well unless you have a special scenario. The first method is easier but may result in slightly higher allocations, though I can't be positive and it completely depends on your object complexity.
     
    jGate99 likes this.
  46. jGate99

    jGate99

    Joined:
    Oct 22, 2013
    Posts:
    1,211
    Thank you very much Dustin :)
     
    Dustin-Horne likes this.
  47. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    You're very welcome.
     
    Zaelot and jGate99 like this.
  48. mons00n

    mons00n

    Joined:
    Sep 18, 2013
    Posts:
    237
    Hi @Dustin-Horne ! Have you attempted to use unity's memory profiler with your package? It includes a compiled version of JsonDotNet2.0 that conflicts with your package due to the following 3 issues:
    Code (CSharp):
    1. Assets/Editor/MemoryProfiler/PackedMemorySnapshotUtility.cs(162,77): error CS0433: The imported type `Newtonsoft.Json.Serialization.DefaultContractResolver' is defined multiple times
    2. Assets/Editor/MemoryProfiler/PackedMemorySnapshotUtility.cs(170,75): error CS0433: The imported type `Newtonsoft.Json.Serialization.ITraceWriter' is defined multiple times
    3. Assets/Editor/MemoryProfiler/PackedMemorySnapshotUtility.cs(138,20): error CS0433: The imported type `Newtonsoft.Json.JsonSerializer' is defined multiple times
    4.  
    If I remove the bundled JsonDotNet20 however, I get a slew of other compiler errors from the memory profiler code. Do you have any suggestions on how I might get the two to play nice with one another? Or how I can namespace off their dll so that it doesn't conflict with yours?
     
  49. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,562
    I'll have to take a look. They must be including an old version or something. What errors do you get if you remove their dll?
     
  50. mons00n

    mons00n

    Joined:
    Sep 18, 2013
    Posts:
    237
    Far too many to list; I think they have some special sauce baked into their DLL - but I could be wrong. I'll take another look tomorrow but I distinctly remember the errors coming from invalid references in their memory profiler methods.
     
unityunity