📅  最后修改于: 2023-12-03 15:18:36.108000             🧑  作者: Mango
When working with Unity, you may need to convert your game objects into JSON format for data storage or transfer purposes. Luckily, Unity provides a built-in method called ToJson
that allows you to easily convert objects into JSON format.
JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate.
JSON can represent two structured types: objects and arrays. An object is an unordered collection of key-value pairs. An array is an ordered collection of values.
ToJson
MethodThe ToJson
method is part of the JSONUtility
class in the UnityEngine
namespace. It takes an object as its argument and returns a JSON string representing that object.
public static string ToJson(object obj);
Here's a basic example of using ToJson
method to convert a Player
object into a JSON string:
using UnityEngine;
public class Player
{
public string name;
public int score;
}
public class Example : MonoBehaviour
{
void Start()
{
Player player1 = new Player();
player1.name = "John";
player1.score = 100;
string json = JsonUtility.ToJson(player1);
Debug.Log(json);
}
}
This will output the following JSON string:
{"name":"John","score":100}
You can also customize the JSON output using the [Serializable]
and [SerializeField]
attributes in your class.
using UnityEngine;
[System.Serializable]
public class Player
{
[SerializeField]
private string playerName = "Default Name";
[SerializeField]
private int playerScore = 0;
}
public class Example : MonoBehaviour
{
void Start()
{
Player player1 = new Player();
player1.name = "John";
player1.score = 100;
string json = JsonUtility.ToJson(player1);
Debug.Log(json);
}
}
This will output the following JSON string:
{"playerName":"John","playerScore":100}
Converting objects to JSON format is a critical part of game development, and the ToJson
method in Unity provides a simple and easy-to-use way of converting objects to JSON. With a basic understanding of JSON and some customization, you can easily convert objects to suit your specific needs.