public static string ToJson (object obj);
public static string ToJson (object obj, bool prettyPrint);

パラメーター

obj JSON 形式に変換するオブジェクト
prettyPrint True の場合、読みやすさのため出力を書式設定します。False の場合、最小サイズの出力の書式設定します。デフォルトは False です。

戻り値

string JSON 形式のオブジェクトのデータ

説明

オブジェクトのパブリックフィールドの JSON 表現を生成します。

Internally, this method uses the Unity serializer; therefore the object you pass in must be supported by the serializer: it must be a MonoBehaviour, ScriptableObject, or plain class/struct with the Serializable attribute applied. The types of fields that you want to be included must be supported by the serializer; unsupported fields will be ignored, as will private fields, static fields, and fields with the NonSerialized attribute applied.

Any plain class or structure is supported, as well as classes derived from MonoBehaviour or ScriptableObject. Other engine types are not supported. (In the Editor only, you can use EditorJsonUtility.ToJson to serialize other engine types to JSON).

Note that while it is possible to pass primitive types to this method, the results may not be what you expect; instead of serializing them directly, the method will attempt to serialize their public instance fields, producing an empty object as a result. Similarly, passing an array to this method will not produce a JSON array containing each element, but an object containing the public fields of the array object itself (of which there are none). To serialize the actual content of an array or primitive type, it is necessary to wrap it in a class or struct.

This method can be called from background threads. You should not alter the object that you pass to this function while it is still executing.

using UnityEngine;

public class PlayerState : MonoBehaviour { public string playerName; public int lives; public float health;

public string SaveToString() { return JsonUtility.ToJson(this); }

// Given: // playerName = "Dr Charles" // lives = 3 // health = 0.8f // SaveToString returns: // {"playerName":"Dr Charles","lives":3,"health":0.8} }