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 JestaBROOK · Apr 12, 2019 at 12:30 AM · jsonserializableutility

[Serialize] Attribute with JSON

I need some clarification on using Json.Utility.ToJson. In the documentation it says that plain classes must include the [Serializable] attribute. However take the following example:

     using System;
     using System.Collections.Generic;
     using UnityEngine;
      
     public class JsonTest : MonoBehaviour
     {
      
         void Start()
         {
             string json = SerializeToJson();
             DeserializeFromJson(json);
         }
      
         string SerializeToJson()
         {
             NonSerializedClass instance = new NonSerializedClass();
             string json = JsonUtility.ToJson(instance);
             Debug.Log(json); // Result: {"valueOne":10,"valueTwo":20}
      
             return json;
         }
      
         void DeserializeFromJson(string json)
         {
             NonSerializedClass instance = JsonUtility.FromJson<NonSerializedClass>(json);
             Debug.Log(instance.valueOne); // Result: 10
         }
     }
 
     public class NonSerializedClass
     {
         public int valueOne = 10;
         public int valueTwo = 20;
     }

In this example, the NonSerializedClass (as the name implies) does not use the [Serializable] attribute, yet it still gets serialized correctly, and deserialized correctly. I would expect this to return empty JSON as a result of not including the attribute.

However, if I try to place the class in a List<> then I get the results I expect, take the following example (NOTE: I still don't include the attribute on the NonSerializedClass):

     using System;
     using System.Collections.Generic;
     using UnityEngine;
      
     public class JsonTest : MonoBehaviour
     {
      
         void Start()
         {
             string json = SerializeToJson();
             DeserializeFromJson(json);
         }
      
         string SerializeToJson()
         {
             List<NonSerializedClass> dataList = new List<NonSerializedClass>();
            
             dataList.Add(new NonSerializedClass();
             dataList.Add(new NonSerializedClass();
             dataList.Add(new NonSerializedClass();
      
             NSList container = new NSList(dataList);
      
             string json = JsonUtility.ToJson(container);
             Debug.Log(json); // Result: {}
      
             return json;
         }
      
         void DeserializeFromJson(string json)
         {
             NSList container = JsonUtility.FromJson<NSList>(json);
             Debug.Log(container[0].valueOne); // Null reference
         }
     }
 

     public class NonSerializedClass
     {
         public int valueOne = 10;
         public int valueTwo = 20;
     }

     // Wrapper
     public class NSList
     {
         public List<NonSerializedClass> dataList;
      
         public NSList(List<NonSerializedClass> _dataList)
         {
             dataList = _dataList;
         }
     }
 

This behaves as expected, and returns an empty JSON and a Null Reference in the deserialization. This can be rectified by including the [Serializable] attribute. But this then begs the following question, how comes the Wrapper class does not need to include the Attribute in this circumstance?

I would like to know the following:

  • Why does my NonSerialized class correctly serialize to JSON without the [Serializable] attribute?

  • When adding the class to a List<> using a wrapper class to serialize the List<>, how comes only the class in the collection needs the attribute, and not the wrapper class?

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

1 Reply

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

Answer by Bunny83 · Apr 12, 2019 at 02:10 AM

The documentation isn't very clear about when you actually need the Serializable attribute. The rules are quite simple: You pass one single object to the serializer. This object will be serialized according to the serialization rules. The root object never need to be marked as Serializable. This is only relevant for the serializer when it processes fields of custom serializable types. So the attribute acts like a "Am I allowed to enter this sub object or not". So the attribute is only relevant for fields of that type.


Keep in mind that the JsonUtility is based on the general serialization rules. Though as i said the root object is always serialized / deserialized as long as it's a class or a struct that contains supported fields. Arrays or Lists are currently not supported as root objects.

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 JestaBROOK · Apr 12, 2019 at 04:01 PM 0
Share

Excellent answer that gives me a clear explanation of the confusion I was having. Thanks.

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

104 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

Related Questions

JsonUtility not found / working 0 Answers

JsonUtility.FromJson cannot convert object from rest call 1 Answer

JsonUtility.ToJson returns empty file 2 Answers

Firebase Datasnapshot Json to Object using JsonUtility 1 Answer

Issues saving file in iOS 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