Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by Ricewind1 · Jun 08, 2015 at 12:06 AM · c#jsondeserializationpolymorphismjsonfx

JsonFX and Polymorphism?

I'm trying to store (readable) data in a text-file as an asset since the class I'm serializing contains many things that Unity itself can't handle.

A problem is though, that even though everything saves and loads, only the base-type is returned. I did a lot of searches on the internet to find a solution and I've tried everything recommended but alas, the problem still resides.

I'm trying to serialize a class with 2 fields, one int and one Dictionary;

Item is the base class with a large variety of children I've had to convert int to string to allow jsonfx to de-serialize the dictionary. The following code is used to serialize and de-serialize the data.

 public static string FiletoJSON(object T)
     {
         try
         {
             StringBuilder sb = new StringBuilder();
 
             JsonWriterSettings settings = JsonDataWriter.CreateSettings(false);
             settings.TypeHintName = "__type";
 
             JsonWriter writer = new JsonWriter(sb, settings);
             writer.Write(T);
             return sb.ToString();
         }
         catch(Exception e)
         {
             Debug.LogWarning(e.InnerException);
             return null;
         }
     }
 
     public static T JSONtoFile<T>(string JSONString)
     {
         try
         {
             JsonReaderSettings settings = JsonDataReader.CreateSettings(true);
             settings.TypeHintName = "__type";
             using (TextReader textReader = new StringReader(JSONString))
             {
                 var jsonReader = new JsonReader(textReader, settings);
                 return jsonReader.Deserialize<T>();
             }
         }
         catch (Exception e)
         {
             Debug.LogWarning(e);
             return default(T);
         }
     }

The following is the output of the string.

 {
     "__type": "ItemDatabase, Assembly-CSharp",
     
     "DatabaseID": 1,
     
     "ItemList": 
         {
             "1": 
                 {
                     "__type": "Sniper, Assembly-CSharp",
                     "MaxAmountOfItem": 1,
                     
                     "RangedAttack": 950,
                     
                     "WeaponObjectID": 3,
                     
                     "weaponType": "Sniper",
                     
                     "Accuracy": 100,
                     
                     "MaxEnergy": 437,
                     
                     "SkillSlots": null,
                     
                     "StatusEffects": null,
                     
                     "EnergyRestorePerTick": 8,
                     
                     "EnergyRestoreOverTime": true,
                     
                     "Variance": 30,
                     
                     "Cooldown": 1,
                     
                     "Name": "TestSniper",
                     
                     "Description": "",
                     
                     "ID": 1,
                     
                     "Points": 1,
                     
                     "Tier": 8
                 }
         }
 }
 

How can I make sure that JsonFX properly de-serializes my sub-types too?

Note: The purpose of this, is storing several dictionaries filled with supertypes. I've managed to accomplish this with a binaryformatter, but there is a noticeable performance reduction compared to using JSON. On top of this, the data in the text file is unreadable.

Comment
Add comment · Show 2
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image crohr · Jun 08, 2015 at 07:34 AM 0
Share

The only thing that stands out to me is are you passing the base-type as the generic parameter to JSONtoFile()? I use polymorphism with JsonFX and as long as I pass in the sub-type as the generic parameter I get the correct object returned.

avatar image Ricewind1 · Jun 08, 2015 at 12:51 PM 0
Share

I am, and in my case it was the ItemDatabase class. Turns out the dictionary was the main problem as it can handle an array just fine. This is about 8 times slower as binary formatting though.

1 Reply

· Add your reply
  • Sort: 
avatar image
1

Answer by Mark Gossage · Jun 08, 2015 at 07:43 AM

Never worked with the JsonReader before, but I have worked with the newtonsoft one & I know that supports polymorphism ok.

I had a base class (Message) with a number of derived classes. I found that I couldn't serilaise a Message polymorphicly, but a Message[] seemed to work just fine.

As for testing: just write a test script:

 void Start()
 {
   Soldier s;
   s=new Sniper(){....};
   string str=JsonToString(s);
   Soldier s2=StringToJson(str);
   if (s2 is Sniper)
   {
      Sniper snip=(Sniper)s2;
      Debug.Log(....);
   }
   else
   {
      Debug.Log("Polymorthism issue");
   }
 }



Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Ricewind1 · Jun 08, 2015 at 12:43 PM 0
Share

The dictionary was the problem, deserializing that only returns Typeof Item. A list can't even be deserialized it seems.

I've ran a few tests with 10.000 Snipers added. Loading the database from Binary took around 265ms Loading the database from JSON (erroneous) took around 850 ms Loading the database from JSON as Item[] and converting it to a dictionary took ~1850 ms.

Storing the data was almost instnat with binary and took a few seconds with JSON eitherway. The JSON file is also 4 times larger in size.

It's clear that binary is the winner here, but this leaves me with unreadable data.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

22 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

An OS design issue: File types associated with their appropriate programs 1 Answer

Deserializing Json String 1 Answer

Multiple Cars not working 1 Answer

Distribute terrain in zones 3 Answers

JsonUtility doesn't serialize nested mixed var 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges