Why did I get an empty JSON string returned when using setter and getter in an object class in Unity 5.3?

I tried to use the new JSON serialization feature in Unity 5.3, and I wrote the following code from the link in the usage example provided on the Unity website. The only thing I did was create the class variables of the objects (FruitItem class in my case) using setter and getter instead of making them pure public variables. By doing this, I only got a pair of curly braces with no content inside. However, if I remove the getter and setter and make the class variables pure public variables, I can get the correct result. Can someone give me some clues why this happened? Thanks in advance for your help.

Code that works correctly:

using UnityEngine; using UnityEditor; using System.Collections; using System; public class testJson : MonoBehaviour { // Use this for initialization void Start () { FruitItem myFruit = new FruitItem (){ name = "apple", price = 52, quantity = 53 }; string jsonString = JsonUtility.ToJson (myFruit); Debug.Log (jsonString); } // Update is called once per frame void Update () { } } [Serializable] public class FruitItem{ //using the pure public variables and the output will be: //{"name":"apple","quantity":53,"price":52} public string name; public int quantity; public int price; } 

Code that does not work correctly:

 using UnityEngine; using UnityEditor; using System.Collections; using System; public class testJson : MonoBehaviour { // Use this for initialization void Start () { FruitItem myFruit = new FruitItem (){ name = "apple", price = 52, quantity = 53 }; string jsonString = JsonUtility.ToJson (myFruit); Debug.Log (jsonString); } // Update is called once per frame void Update () { } } [Serializable] public class FruitItem{ //using the pure public variables and the output will be: //{} public string name{ get; set;} public int quantity{ get; set;} public int price{ get; set;} } 
+5
source share
1 answer

Unity cannot serialize properties.

http://docs.unity3d.com/ScriptReference/SerializeField.html

The serialization system used can perform the following actions:

  • CAN serializes public non-static fields (serializable types)
  • CAN serializes non-public non-static fields marked with the [SerializeField] attribute.
  • CANNOT serialize static fields.
  • CANNOT serialize properties.

Your field will only be serialized if it is a type that Unity can serialize:

Serializable Types:

  • All classes inheriting from UnityEngine.Object, for example, GameObject, Component, MonoBehaviour, Texture2D, AnimationClip.
  • All basic data types, such as int, string, float, bool.
  • Some built-in types, such as Vector2, Vector3, Vector4, Quaternion, Matrix4x4, Color, Rect, LayerMask.
  • Serializable Arrays
  • List of serializable type
  • Transfers
  • Structures
+15
source

Source: https://habr.com/ru/post/1238175/


All Articles