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. Grinchi

    Grinchi

    Joined:
    Apr 19, 2014
    Posts:
    130
  2. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    Send me a PM with your email address and I'll send you the current build.
     
  3. mcmorry

    mcmorry

    Joined:
    Dec 2, 2012
    Posts:
    580
    Hi I have an issue with my serialization.
    I have a dictionary that has as key a struct with some enum public fields:
    Code (CSharp):
    1. // the Key of the dictionary
    2. public struct GoalID {
    3.     public GoalGroups GoalGroup;
    4.     public GoalSubGroups GoalSubGroup;
    5.     public GoalTypes GoalType;
    6. }
    7.  
    8. // The value
    9. public class GoalProgress {
    10.     public GoalID ID;
    11.     public int InternalLevel;
    12.     public float RequiredValue;
    13.     public float CurrentValue;
    14.     public bool Active;
    15. }
    16.  
    17. // the dictionary
    18. Dictionary<GoalID, GoalProgress> Goals;
    When I serialize I get a very weird json that can't be deserialized back:
    Code (JavaScript):
    1.  
    2.         "GoalsProgress": {
    3.           "GoalID": {
    4.             "ID": {
    5.               "GoalGroup": 0,
    6.               "GoalSubGroup": 1,
    7.               "GoalType": 1
    8.             },
    9.             "InternalLevel": 0,
    10.             "RequiredValue": 1000.0,
    11.             "CurrentValue": 1000.0,
    12.             "Active": false
    13.           },
    14.           ...
    15.  
    What should I do to make the Key serialized correctly? Now looks like that there is just the Type name of the struct instead of the values.
    Thanks
     
    Last edited: Jan 25, 2016
  4. mcmorry

    mcmorry

    Joined:
    Dec 2, 2012
    Posts:
    580
    Resolved :)
    I wrote a TypeCoverter to serialize the struct back and forward to a string with its values.
     
    Dustin-Horne likes this.
  5. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    That's exactly what I was going to do for you, or write a JsonConverter. :) Because you weren't using a primitive type for the key the generated json wasn't going to be valid, but you can convert that back and forth to and from a primitive value which is what you did.
     
    mcmorry likes this.
  6. hangar

    hangar

    Joined:
    Feb 1, 2013
    Posts:
    21
    We're getting an error in an iOS build:
    ExecutionEngineException: Attempting to call method 'Newtonsoft.Json.Utilities.CollectionWrapper`1[[System.Int32, mscorlib, Version=2.0.5.0, Culture=, PublicKeyToken=7cec85d7bea7798e]]::.ctor' for which no ahead of time (AOT) code was generated.

    I tried adding a link.xml exception, but that didn't seem to work. (Does link.xml not work for code compiled into Assembly-CSharp?)
     
  7. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    Is this in IL2CPP? Which platform and Unity version? The link.xml change should work, but Unity's stripping seems really finicky, especially with IL2CPP where some kind of stripping is always on by default. Worst case, I should be able to throw a Preserve attribute on that class / constructor to prevent it from being stripped.
     
  8. hangar

    hangar

    Joined:
    Feb 1, 2013
    Posts:
    21
    Yes, IL2CPP. Unity is 5.3.1p1, though we'll upgrade to 5.3.2 pretty soon. It's getting compiled into Assembly-CSharp, so it could be that none of the dozen variations I used for link.xml worked. This is what I ended up with:

    <assembly fullname="Assembly-CSharp">
    <type fullname="*" preserve="all"/>
    </assembly>

    Supposedly they improved the stripping error messages in 5.3.2 (finally). Wish they'd print out what actually got removed or something.
     
  9. Tinjaw

    Tinjaw

    Joined:
    Jan 9, 2014
    Posts:
    518
    RE: "Note: GameObjects and MonoBehaviors cannot be serialized directly as well as some built in classes (such as Texture2D that doesn't have a public parameterless constructor) but they are simple to serialize using either proxy classes or creating a custom ContractResolver or JsonConverter. "

    I have a NetworkBehaviour class that I would like to serialize. I do not understand the note above. Are there any examples available that I could use to learn about proxy classes or custom JsonConverters?
     
  10. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    Ok I'll take a look and see if I can come up with a quick fix / workaround.

    You would need to have some sort of "Save" method that you can call. You'd need to create a class that has the same properties as the object you want to serialize and copy the values from your object to the "proxy" object (or copy). Then serialize that. For deserialization you'll need to construct the NetworkBehaviour class, deserialize your proxy, then copy the values back over. Doing it this way doesn't require you to use a custom JsonConverter. Does that answer your question?
     
  11. Tinjaw

    Tinjaw

    Joined:
    Jan 9, 2014
    Posts:
    518
    Ah! Now I understand what you mean by proxy. I think I can do that.

    Is there any advantage to using a JsonConverter over a proxy?
     
  12. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    Not really. You still have to use a custom proxy object either way. One thing it can help though is that you can create a custom converter for the NetworkBehaviour type and have it automatically copy stuff over to the proxy and serialize the proxy for you. Deserialization would still be tricky though because you wouldn't know what to attach it to. That being said, depending on what the properties are, as long as your proxy object (or at least the generated json) has the same property names as your NetworkBehavior, in order to load it, you could use JsonConvert.PopulateObject(existingBehaviour, jsonString) and it will take the existing instance and populate the properties.
     
  13. Tinjaw

    Tinjaw

    Joined:
    Jan 9, 2014
    Posts:
    518
    That should help. It's almost quitting time here. I will try this tomorrow morning when I return to work. Thank you.
     
    Dustin-Horne likes this.
  14. Ben-BearFish

    Ben-BearFish

    Joined:
    Sep 6, 2011
    Posts:
    1,204
    @Dustin Horne I'm downloading a WWW JSON file and deserializing it with your plugin. I'm getting an exception error because the file is saved as UTF-8, but ANSI seems to work. Is there a way for me to tell it to convert for either ANSI or UTF-8?
     
  15. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    UTF8 shouldn't be a problem. However, it's possible that your UTF-8 data has a BOM (byte order mark) at the beginning of it. What is the exception that you're getting?
     
  16. Ben-BearFish

    Ben-BearFish

    Joined:
    Sep 6, 2011
    Posts:
    1,204
    I don't remember the exact error, it's hard to find now because we told the people on the server to save the files as ANSI from Notepad and it worked. But if I recall it was related to BOM as you mentioned. Is there a solution for that?
     
  17. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    Well, yeah. It depends on how those files are being generated. For instance, in Notepad++ you can save the files as UTF8 Encoding either with or without BOM (they are in the encoding options). The best solution would be to make sure those markers aren't there when generating the files. But if it's there you can handle it. If you want to handle it conditionally you can. I currently don't do it automatically because it would add extra overhead, but I may consider it in the future deeper in the asset where it actually uses a stream reader. Here is the code you'll need... I would recommend caching the Preamble (byte order mark string) so you're not regenerating it every time:

    Code (csharp):
    1.  
    2. var bomString = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());
    3.  
    4. if(jsonString.StartsWith(bomString)) {
    5.      jsonString = jsonString.Remove(0, bomString.Length);
    6. }
    7.  
    This may result in some extra allocation which is why you're better off encoding the file without the BOM in the first place, or stripping the BOM from the string before you return it from the server.
     
  18. Tinjaw

    Tinjaw

    Joined:
    Jan 9, 2014
    Posts:
    518
    Unity 5.2.4f1
    JSON dot NET for Unity version: 1.5.0 ??

    When attempting to serialize my object I get a StackOverflow Exception.

    Code (CSharp):
    1. StackOverflowException
    2. UnityEngine.Color.get_linear () (at C:/buildslave/unity/build/artifacts/generated/common/runtime/MathBindings.gen.cs:662)
    3. (wrapper dynamic-method) UnityEngine.Color.Getlinear (object) <IL 0x00006, 0x00079>
    4. Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue (object) (at Assets/JsonDotNet/Source/Serialization/DynamicValueProvider.cs:104)
    5. Rethrow as JsonSerializationException: Error getting value from 'linear' on 'UnityEngine.Color'.
    6. Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue (System.Object target) (at Assets/JsonDotNet/Source/Serialization/DynamicValueProvider.cs:108)
    7. 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/JsonDotNet/Source/Serialization/JsonSerializerInternalWriter.cs:338)
    8. UnityEngine.EventSystems.EventSystem:Update()
    9.  
    This is the first time I have really tried to use this asset, so I would like some help troubleshooting this. At this point I don't even know if the error is in my code or the asset's. What steps should I take to make progress on this.
     
  19. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    @Tinjaw The problem is the object you're trying to serialize. In order to serialize it you're going to have to either create a custom JsonConverter or create a proxy object that has the properties you're interested in. The problem is that the Color class has properties that return another Color class. For instance:

    Color.liner, Color.gamma, Color.grayscale, Color.maxColorComponent. Color also implements an indexer so you can say: myColor[0], myColor[1], myColor[2], or myColor[3] which return the r, g, b and a values respectively. So, when the serializer tries to serialize the color object, it tries to serialize those properties which also return a Color object, then it tries to serialize those which have the same properties and also return Color objects and you end up with an issue of infinite recursion, hence the stack overflow.
     
  20. Tinjaw

    Tinjaw

    Joined:
    Jan 9, 2014
    Posts:
    518
    OK. Where can I find documentation and/or example of doing that?

    Thanks for the quick reply.
     
  21. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
  22. Tinjaw

    Tinjaw

    Joined:
    Jan 9, 2014
    Posts:
    518
    Thanks. I've got my homework to do now. I'll check in with you tomorrow, good or bad. Thanks.
     
  23. darkanum

    darkanum

    Joined:
    Dec 16, 2011
    Posts:
    7
    How can i deserialize a Www.text into a object?
     
  24. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    ?? I guess that depends on what is in your WWW.text. as long as you have an object that matches the json: JsonConvert.DeserializeObject<YouObjectType>(textwithjson)
     
  25. Freewillkr

    Freewillkr

    Joined:
    Nov 11, 2014
    Posts:
    1
    Unity v5.2.2p4
    Json .Net for Unity 1.5.0

    Platform : Samsung TV

    Bulid Error.
    Assets/JsonDotNet/Source/Linq/JPropertyDescriptor.cs(164,27): error CS0115: `Newtonsoft.Json.Linq.JPropertyDescriptor.NameHashCode' is marked as an override but no suitable property found to override

     
    Last edited: Feb 18, 2016
  26. Tinjaw

    Tinjaw

    Joined:
    Jan 9, 2014
    Posts:
    518
    @Dustin Horne

    Progress. I think I have implemented enough of a custom converter to handle the color struct. At least I am getting past that. Now I am getting a different error when trying to serialize my custom class.

    Code (CSharp):
    1. NotSupportedException: rigidbody property has been deprecated
    2. UnityEngine.GameObject.get_rigidbody () (at C:/buildslave/unity/build/Runtime/Export/UnityEngineGameObject_Deprecated.cs:23)
    3. (wrapper dynamic-method) UnityEngine.GameObject.Getrigidbody (object) <IL 0x00006, 0x00073>
    4. Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue (object) (at Assets/JsonDotNet/Source/Serialization/DynamicValueProvider.cs:104)
    5. Rethrow as JsonSerializationException: Error getting value from 'rigidbody' on 'UnityEngine.GameObject'.
    6. Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue (System.Object target) (at Assets/JsonDotNet/Source/Serialization/DynamicValueProvider.cs:108)
    7. 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/JsonDotNet/Source/Serialization/JsonSerializerInternalWriter.cs:338)
    8. UnityEngine.EventSystems.EventSystem:Update()
    Any idea how to handle this one?
     
  27. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    Rigid body is the same way. This is the reason some of the built in types like Monobehaviour isn't supported out of the box. The transforms will bite you. However, I am looking into adding custom converters for these types to be bundled with a future release.
     
  28. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    I don't yet officially support Samsung TV as I have no way to test, but send me an email (email address is in readme.txt) and I'll see if I can work with you on getting it supported.
     
  29. Tinjaw

    Tinjaw

    Joined:
    Jan 9, 2014
    Posts:
    518
    I was just going to suggest/request this from you. Please consider me as a Beta tester when you get there.
     
  30. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    Thanks, will do! It's going along with a larger update as well, updating the JSON .NET version. I started migrating to 7.0 but I'm considering moving up to 8 now that it's released, however I'm not sure if it fully supports .NET 3.5 which would be an issue so it's investigatory. It's on the backburner at the moment while I try to work around some Unity bugs as well.
     
  31. AnikKhoma

    AnikKhoma

    Joined:
    Apr 10, 2014
    Posts:
    10
    Last edited: Feb 19, 2016
  32. Bouillie

    Bouillie

    Joined:
    Feb 19, 2016
    Posts:
    1
    Hi, I'm having problems the deserialization of properties on Android with stripping, just like that post : http://forum.unity3d.com/threads/json-net-for-unity.200336/page-15#post-2056261

    I'm using Unity 4.6.8f1, with no subset, and stripping bytecode. I've tried a fix on ReflectionUtils.GetMemberValue :

    Code (CSharp):
    1. #if !(UNITY_IOS || UNITY_WEBGL || UNITY_XBOXONE || UNITY_XBOX360 || UNITY_PS4 || UNITY_PS3 || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID)
    2.              return ((PropertyInfo)member).GetValue(target, null);
    3. #else
    4.            
    5.              var getMethod = ((PropertyInfo) member).GetGetMethod(true);
    6.              return getMethod.Invoke(target, null);
    7. #endif

    As you can see, I just added UNITY_ANDROID to the list of preprocessor to use the alternative method. It seems to work. I don't know if there are others places in Json.net where that fix is needed.

    Do you think that it's the right fix ? If so, can you release a new version with it ?
     
    Last edited: Feb 19, 2016
  33. Ryan-Hayle

    Ryan-Hayle

    Joined:
    Feb 16, 2014
    Posts:
    142
    Could someone tell me how I would deserialize the below string? The data is external and not serialize by me.

    string test = "{\"activities-heart\":[{\"dateTime\":\"2016-02-18\",\"value\":{\"customHeartRateZones\":[],\"heartRateZones\":[{\"caloriesOut\":1268.5113,\"max\":92,\"min\":30,\"minutes\":743,\"name\":\"Out of Range\"},{\"caloriesOut\":928.8468,\"max\":128,\"min\":92,\"minutes\":145,\"name\":\"Fat Burn\"},{\"caloriesOut\":21.4389,\"max\":156,\"min\":128,\"minutes\":2,\"name\":\"Cardio\"},{\"caloriesOut\":0,\"max\":220,\"min\":156,\"minutes\":0,\"name\":\"Peak\"}],\"restingHeartRate\":61}}]}";

    Thanks!
     
  34. Ryan-Hayle

    Ryan-Hayle

    Joined:
    Feb 16, 2014
    Posts:
    142
    I have just worked it out, DeserializeObject doesn't know how to handle the dashes I am receiving.
    e.g. activities-heart
     
  35. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    There's no a simple answer to that. When I first did my conversion, 5.0 was just coming out but 4.3 was the easiest to get working with Unity so the asset was 4.3. Then Unity added support for Windows 8 and Windows Phone 8 which needed a higher version. So, the base asset for most platforms is 4.3, but the WinRT branch is 5.0r8. Then, Windows 10 Universal support was added which I haven't officially released yet, but that is currently the version 7 line.

    All of that being said, I have also made a lot of customizations and tweaks specific to Unity, as well as workarounds for Unity bugs in various versions, and shimming in some missing functionality. I have also taken some bug fixes from subsequent official releases and backported them. So it isn't a pure version in that sense.

    I am working on unifying the release and getting everything at the very least to the v7 iteration. I'm investigating v8 but I have to make sure it fully supports .NET 3.5.
     
    Tinjaw likes this.
  36. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    Ryan - I just replied to your email and gave you some instructions on how to handle this (and a resource link) as well. The key would be to use:
    Code (csharp):
    1.  
    2. [JsonProperty(PropertyName="activities-heart")]
    3.  
    And then use a property name that is valid in C# for the real property.
     
  37. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    Awesome, I think that's the only place where that would be necessary. I've seen this happen before. I have no idea why Unity is stripping that. Glad you got it working. In the future, all platforms will be IL2CPP enabled so that fix you made would actually just naturally apply.
     
  38. AnikKhoma

    AnikKhoma

    Joined:
    Apr 10, 2014
    Posts:
    10
    Thank you for your work, I appreciate it
    But before buying your Asset I would like to know specifically about this point
    Thank you
     
  39. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    I can certainly double check it for you just to make sure, though I don't think it's an issue but let me verify. In regards to that post, JsonSchema is an entirely separate (and commercial) product from Newtonsoft so the schema generator tools won't ever be included with my asset.

    Essentially what you're asking is if you have json like:
    { "SomeProp" : 1.0 }
    You want to know that SomeProp can be of type int and it will correctly deserialize correct?
     
  40. Tinjaw

    Tinjaw

    Joined:
    Jan 9, 2014
    Posts:
    518
    @Dustin Horne

    After some research, it looks like rigidbody was deprecated. It is still showing up when Newtonsoft collects all the properties of a type (and it should show up because it is deprecated, not removed). When it attempts to then use the getter (get_rigidbody) that doesn't throw a *warning* that it is deprecated, but instead throws an *exception*, thus collapsing the whole call stack.

    Does that make sense? Should I be reporting this to Newtonsoft? Unity?

    I cannot correct this as I don't have access to Unity's source code, correct?

    ==Follow up==
    RE: http://www.newtonsoft.com/json/help/html/ConditionalProperties.htm
    Since I don't have access to the source code for type, I can't implement this. Is there some way to add this as a parameter on the JsonConvert.SerializeObject call -- kind of like passing in a converter on the JsonSerializerSettings?
     
  41. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    Yes it was deprecated but not removed. It's also not the only property that will cause problems. It's not a bug in JSON .NET, the problem is the way that Unity has overridden the Equals (==) operator. From what I've been able to figure out, every GameObject actually has a rigidbody attached to it, which probably looks something like this:

    Code (csharp):
    1.  
    2. public class rigidBody
    3. {
    4.     private bool Initialized {get; set;}
    5. }
    6.  
    So, when you "add" a rigidbody to your game object, it gets "Initialized" set to true... or sees that it's initialized. So I your unity code (pre-deprecation) you could say:

    Code (csharp):
    1.  
    2. if(gameObject.rigidbody)
    3. {
    4.     //Do something
    5. }
    6.  
    Since Unity has overridden those operators, it can return null during that if check. However, when examining the properties via Reflection, Json .NET can actually see that a rigidbody object exists and tries to serialize it. Unity then throws an exception because you're trying to access an uninitialized rigidbody. That was Unity's design decision which poses some unique challenges.

    I think it's also part of the reason they deprecated the property (amongst other helper properties)... but it still exists. This is also why monobehaviours, gameobjects, etc. aren't supported directly for serialization. That and the fact that you can't deserialize them because you can't properly recreate them along with their attached components.

    So, the only way you can handle this again is to create a custom converter, or you can create a custom class that has the same properties that you care about. Then you can add a SerializeComponent or something to your gameobject which will copy the properties to the "proxy" class and serialize that instead without the extra junk that can't be serialized directly.
     
  42. Tinjaw

    Tinjaw

    Joined:
    Jan 9, 2014
    Posts:
    518
    From what I read, it is to separate out the physics stuff from generic GameObjects.

    Thanks for the detailed reply. That makes things much clearer now. I will start to catalog the values that I need and only serialize those. Thank you.
     
    Dustin-Horne likes this.
  43. AnikKhoma

    AnikKhoma

    Joined:
    Apr 10, 2014
    Posts:
    10
    Thanks
    No. Look at this schema:
    Code (JavaScript):
    1. {
    2.   "type": "object",
    3.   "properties": {
    4.     "singleField": {
    5.       "type": "number"
    6.     }
    7.   }
    8. }
    Validator expected "number"
    Json creation:
    Code (JavaScript):
    1. var obj;
    2. obj.singleField = 1.0//look like number?
    3. console.log(JSON.stringify(obj));
    Output:
    Code (JavaScript):
    1. {
    2.     "singleField": 1//now integer
    3. }
    JSON.Net expect "number", but got "integer"
    i.e. i wont to assign integer in to float, not vice versa
    This is fixed in official later JSON.Net versions
     
  44. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    ahh, so ignoring the javascript bit, essentially you want to have:

    Code (csharp):
    1.  
    2. public class SomeObject
    3. {
    4.     public float singleField {get; set;}
    5. }
    6.  
    Then you have this Json string:

    Code (csharp):
    1.  
    2. {
    3.    "singleField": 1
    4. }
    5.  
    And you want to do:

    Code (csharp):
    1.  
    2. JsonConvert.DeserializeObject<SomeObject>(jsonString);
    3.  
    And the concern is that an error will be thrown because the value won't appropriately translate to float.
     
  45. AnikKhoma

    AnikKhoma

    Joined:
    Apr 10, 2014
    Posts:
    10
    Yes, this is it
    Here is additional sample code
    On old version of JSON.Net (error will be throwed)
    Code (CSharp):
    1. using Newtonsoft.Json;
    2. using Newtonsoft.Json.Schema;
    3.  
    4. public class JSSchemaTest {
    5.     class TestClass
    6.     {
    7.         public float field = 20;
    8.     }
    9.     JsonSchemaGenerator generator = new JsonSchemaGenerator();
    10.     JsonSerializer serializer = new JsonSerializer();
    11.     public void Run () {
    12.         JsonSchema schema = generator.Generate(typeof(TestClass));
    13.         JsonTextReader reader = new JsonTextReader(new System.IO.StringReader("{field: 2}"));
    14.         JsonValidatingReader validatingReader = new JsonValidatingReader(reader);
    15.         validatingReader.Schema = schema;
    16.         TestClass res = serializer.Deserialize<TestClass>(validatingReader);
    17.     }
    18. }
    And on newest versions (no errors):
    Code (CSharp):
    1. using Newtonsoft.Json;
    2. using Newtonsoft.Json.Schema;
    3. using Newtonsoft.Json.Schema.Generation;
    4.  
    5. public class JSSchemaTest
    6. {
    7.     class TestClass
    8.     {
    9.         public float field = 20;
    10.     }
    11.     JSchemaGenerator generator = new JSchemaGenerator();
    12.     JsonSerializer serializer = new JsonSerializer();
    13.  
    14.     public void Run()
    15.     {
    16.         JSchema schema = generator.Generate(typeof(TestClass));
    17.         JsonTextReader reader = new JsonTextReader(new System.IO.StringReader("{field: 2}"));
    18.         JSchemaValidatingReader validatingReader = new JSchemaValidatingReader(reader);
    19.         validatingReader.Schema = schema;
    20.         TestClass res = serializer.Deserialize<TestClass>(validatingReader);
    21.     }
    22. }
     
    Last edited: Feb 20, 2016
  46. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    That scenario doesn't make sense though. You're specifically using JsonSchema and the JSchemaValidatingReader. That isn't part of Json .net, that is part of JsonSchema. It's a commercial add-on product for json .net from Newtonsoft and isn't part of my asset.
     
  47. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
  48. SenseEater

    SenseEater

    Joined:
    Nov 28, 2014
    Posts:
    84
    is it possible to serialize objects with delegates ? i mean i have classes with delegates fields that i assign with anonymous method. i would like to define the delegate once on initialization and then serialize it to json and every-time i deserialize the objects , the respective delegate fields should load with appropriate methods.
     
  49. AnikKhoma

    AnikKhoma

    Joined:
    Apr 10, 2014
    Posts:
    10
    Oh sorry..
    What else is there a way to use json schema in unity?
    Or any other method of rigorous validation?
    In general, I love protobuf, but now forced to use json
     
  50. Dustin-Horne

    Dustin-Horne

    Joined:
    Apr 4, 2013
    Posts:
    4,568
    Not strict validation, no. JSON .NET by default is a validating serializer but it's not strict validation. It follows a lot of the coercion rules that JavaScript does, such as 1 and "1" both being deserializable to an integer. Protobuf is nice, but it's also ordinal and strictly schema dependent if I recall, so a change in your class definition, especially if properties are reordered, can very easily be breaking.