I tried to use the new JSON serialization feature in Unity 5.3, and I wrote the following code by reference the usage example provided On Unity website. The only different part that I made was creating the variables of the object class (FruitItem class in my case) by using setter and getter instead of making them pure public variables. By doing this, I only got a pair of braces without any contents inside. However, if I delete the getter and setter and make the class variables to be pure public variables, I will be able to get the correct result. Can anybody provide any hints to me why that happened? Thanks in advance for your help.
Code that works properly:
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 doesn't work properly:
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;}
}
Unity can not serialize properties.
http://docs.unity3d.com/ScriptReference/SerializeField.html
The serialization system used can do the following:
Your field will only serialize if it is of a type that Unity can serialize:
Serializable types are:
EDIT: Only plain classes and structures are supported; classes derived from UnityEngine.Object (such as MonoBehaviour or ScriptableObject) are not.
https://docs.unity3d.com/ScriptReference/JsonUtility.FromJson.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With