Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
2 captures
12 Jun 22 - 14 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 /
  • Help Room /
This question was closed May 02, 2018 at 02:45 PM by tormentoarmagedoom for the following reason:

The question is answered, right answer was accepted

avatar image
1
Question by Senuska · Aug 30, 2017 at 05:41 PM · serializationjsoninheritancepolymorphismderived-class

[SOLVED] JSON Serialization of Derived Classes

Hello all. I am trying to serialize a list of results into a JSON string. I have a base class for all of my results, and have a few derived classes that add additional data members. I was looking at the JSON string and only saw that the base class data members were being written to the file.

 [System.Serializable]
 public class BaseResult {
     public string name;
     public enum ResultType {
         None,
         Accepted,
         Denied
     };
     public ResultType type;
 
     public BaseResult(){
         name = "base";
         type = ResultType.None;
     }
 }

 [System.Serializable]
 public DerivedResultA : BaseResult {
     public int input;

     public DerivedResultA() : base() {
         name = "derivedResult";
         input = 0;
     }
 }

 [System.Serializable]
 public GameResults {
     public List<BaseResults> results;
     public GameResults(){
         results = new List<BaseResult>();
     }
     public Add(BaseResult b){
         results.Add(b);
     }
 }

 private GameResults g_results;

 void Start() {
     for(int i = 0; i < 10; i++) {
         g_results.results.Add(new DerivedResultA());
     }

     string jsonOut = JSONUtility.ToJson(results);

     Debug.Log(jsonOut);
 }
 

Would output the following JSON:

 {
     "results":
     [
         {
             "name" : "derivedResult",
             "type" : 0
         },
         ...
         {
             "name" : "derivedResult",
             "type" : 0
         }
     ]
 }

Will I have to parse the results collection and have a switch statement to cast the list member as the derived class to get the data members of the derived class serialized?

Comment
Add comment
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

2 Replies

  • Sort: 
avatar image
4
Best Answer

Answer by Senuska · Aug 30, 2017 at 06:55 PM

It seems that Unity's Json Serialization is sub-par. I will have to make some very hacky conditionals and loops to have the Json Serializer actually serialize the data I have.

Example method:

 string HackyToJson(GameResults gr)
 {
     string resultsJson = "";
     resultsJson += "{\"results\":[";
     for (int i = 0; i < gr.results.Count; i++)
     {
         if (gr.results[i].name == "derivedResultA")
         {
             resultsJson += JsonUtility.ToJson(((DerivedResultA)gr.results[i]));
         }
         if (i < gr.results.Count - 1)
         {
             resultsJson += ",";
         }
     }
     resultsJson += "]}";

     return resultsJson;
 }

Edit: The other way to fix this problem is to use the (JSON.Net) library. It properly serializes derived classes, and it is well supported.

Comment
Add comment · 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
1

Answer by Judgeking · May 02, 2018 at 06:29 AM

I had a similar problem, I solved it by explicitly using the Serializable attribute on my classes

 using System;
 
 [Serializable]
 public class GameSettings {
     public float pacManSpeed = 15;
     public float powerPelletTime = 7;
     public GhostSetting inkySetting = new GhostSetting();
     public GhostSetting blinkySetting = new GhostSetting();
     public GhostSetting pinkySetting = new GhostSetting();
     public GhostSetting clydeSetting = new GhostSetting();
 }
 
 [Serializable]
 public class GhostSetting {
     public float speed = 5;
     public int aggression = 5;
 }
 

Comment
Add comment · Show 4 · 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 bourriquet · Dec 28, 2018 at 05:07 PM 2
Share

This has nothing to do with what the question is about.

avatar image Judgeking bourriquet · May 15, 2019 at 06:36 AM 0
Share

Yeah, it does, try reading, I had the same problem and solved it, but thanks for the downvote ah.

avatar image bourriquet Judgeking · Jun 13, 2019 at 04:16 PM 3
Share

OP already has explicit [Serializable] attributes on all his classes, but he is asking about derived classes serialization. There are no derived classes in your code.

avatar image Skyunity · Mar 09, 2021 at 01:09 AM 0
Share

This fixed my problem. Thank you.

Follow this Question

Answers Answers and Comments

120 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 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 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 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 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 avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Create a list of BaseType where different supertypes are contained. 0 Answers

Get reference to dynamically added script 1 Answer

UnityException: Failed to run serialization 0 Answers

Script execution order of child and parent classes - Parent then children??? 1 Answer

Setting components variables with another component 0 Answers


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