Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 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 tr808axm · Jan 19, 2017 at 10:35 PM · c#json

Doesn't JsonUtility support arrays with abstract type?

The "new" class JsonUtility provides easy-to-use JSON (de-)serialization. In this "early" state, it doesn't support arrays as type to directly serialize. However, there is a workaround using wrapper classes (as seen in this post on StackOverflow). In my project, I have an array of objects that extend an abstract class, but JsonUtility doesn't seem to do anything with it.

 using System;
 using UnityEngine;
 
 public class JsonTest : MonoBehaviour {
     void Start () {
         // The array that contains elements based on AbstractBase
         AbstractBase[] array = new AbstractBase[]
             {
                 new SubOne(),
                 new SubTwo()
             };
 
         // Print one element
         string json = JsonUtility.ToJson(array[0]);
         Debug.Log(json);
 
         // Print array
         json = JsonUtility.ToJson(array);
         Debug.Log(json);
 
         // Print random array (that does not have an abstract class as it's type) using wrapper
         ArrayWrapper<string> stringWrapper = new ArrayWrapper<string>();
         stringWrapper.items = new string[] { "one", "two"};
         json = JsonUtility.ToJson(stringWrapper);
         Debug.Log(json);
 
         // Print abstract array using wrapper
         ArrayWrapper<AbstractBase> abstractWrapper = new ArrayWrapper<AbstractBase>();
         abstractWrapper.items = array;
         json = JsonUtility.ToJson(abstractWrapper);
         Debug.Log(json);
     }
 }
 
 public class ArrayWrapper<T>
 {
     public T[] items;
 }
 
 [Serializable]
 public abstract class AbstractBase
 {
     public string name;
 }
 
 [Serializable]
 public class SubOne : AbstractBase
 {
     public int someImportantInt = 2;
 }
 
 [Serializable]
 public class SubTwo : AbstractBase
 {
     public string someImportantString = "I'm important!";
 }
 

The log prints the following json-strings:

 {"name":"","someImportantInt":2}
 {}
 {"items":["one","two"]}
 {}

This points out that JsonUtility doesn't serialize bare arrays (as seen in line 2) and arrays with an abstract type.

So, is this a bug or does anyone know a workaround for this?

Comment
Add comment · Show 1
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 ComradeVanti · May 27, 2017 at 07:26 PM 0
Share

Please, mighty unity gods shine upon us and give us an answer!

Have you found anything in the meantime?

1 Reply

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by Bunny83 · May 27, 2017 at 08:53 PM

The JsonUtility class has the same restrictions as Unity's serialization system. That means no support for polymorphism. Objects are deserialized based on the reference type. The JSON representation doesn't contain any type information.

Imagine this example:

 [Serializable]
 public class Base
 {
     public int test;
 }
 
 [Serializable]
 public class ClassA : Base
 {
     public string additionalData;
 }
 
 [Serializable]
 public class ClassB : Base
 {
     public string additionalData;
 }
 
 [Serializable]
 public class Wrapper
 {
     public Base[] instances;
 }
 
 var data = new Wrapper();
 data.instances = new Base[3];
 data.instances[0] = new ClassA(){test = 42, additionalData = "foobar"};
 data.instances[1] = new ClassB(){test = 0, additionalData = "some data"};
 data.instances[2] = new Base(){test = 2};

An example JSON representation would be:

 {
     "instances" : [
         { "test" : 42, "additionalData" : "foobar" },
         { "test" : 0, "additionalData" : "some data" },
         { "test" : 2 },
     ]
 }

As you can see the deserializer can't determine the concrete type of the instances inside the array. Unity's serialization system (as well as the JsonUtility class) deserializes the objects based on the variable type. That means after deserialization the Wrapper class would contain 3 Base class instances.

In order to correctly deserialize polymorphic object graphs, the JSON representation would need additional meta data about the actual types involved which is not 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

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

9 People are following this question.

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

Related Questions

Multiple Cars not working 1 Answer

Distribute terrain in zones 3 Answers

Instantiate a sprite using json data value (C# Unity) 2 Answers

JsonUtility with openweatherAPI 1 Answer

Generate Json from Class Type List 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