using Newtonsoft.Json;
using System.Threading;
using UnityEngine;
using System.Collections;

public class JsonAsync : MonoBehaviour
{
    // 异步序列化
    public IEnumerator SerializeAsync<T>(T obj, System.Action<string> callback)
    {
        string json = null;
        bool isDone = false;

        // 在后台线程执行序列化
        Thread thread = new Thread(() =>
        {
            try
            {
                json = JsonConvert.SerializeObject(obj);
            }
            finally
            {
                isDone = true;
            }
        });

        thread.Start();

        // 等待线程完成
        while (!isDone)
        {
            yield return null;
        }

        callback?.Invoke(json);
    }

    // 使用示例
    IEnumerator Start()
    {
        var data = new { Name = "Unity", Value = 2023 };

        yield return SerializeAsync(data, (json) =>
        {
            Debug.Log("Serialized: " + json);
        });
    }
}