AceLand Unity Packages
  • Home
  • Getting Started
    • Installation
    • Project Settings
    • Architecture Graph
    • Development Level
  • Tutorial
    • Create Your Package
    • Create Project Settings
  • Packages
    • Library
      • Change Log
      • Editor Tools
      • Mono
        • Follow Object
        • Singleton
      • Attributes
        • Conditional Show
        • Inspector Button
        • ReadOnly Field
      • Build Leveling
      • CVS
      • DataTools
      • Disposable Object
      • Extensions
      • Json
      • Kalman Filter
      • Optional
      • Project Setting
      • Serialization Surrogate
      • Utils
    • Event Driven
      • Change Log
      • Event Bus
      • Signal
    • Input
      • Change Log
    • Memento Service
      • Change Log
    • Node Framework
      • Change Log
      • Mono Node
    • Node For Mono (dev)
    • Player Loop Hack
      • Change Log
    • Pool
      • Change Log
    • Security (dev)
    • States
      • Change Log
    • Task Utils
      • Change Log
    • WebRequest
      • Change Log
Powered by GitBook
On this page
  • What is JSON?
  • Features
  • Json Converters
  • Create a Serializable Object for Newtonsoft.Json
  • Serialization (Object to JSON)
  • Deserialization (JSON to Object)
  • JSON Validation
  • Error Handling
  • Best Practices
  • Using with Promise Awaiter
  • Benefits of Promise Awaiter
  1. Packages
  2. Library

Json

A lightweight extension that provides asynchronous JSON serialization and validation functionality, specifically designed for Unity projects.

What is JSON?

JSON (JavaScript Object Notation) is a lightweight, text-based data interchange format. It's easy for humans to read and write, and easy for machines to parse and generate. JSON is language-independent and has become one of the most popular data formats for web services and APIs.

{
    "string": "Hello World",
    "number": 42,
    "boolean": true,
    "array": [1, 2, 3],
    "object": {
        "key": "value"
    },
    "null": null
}

Features

  • Asynchronous JSON serialization and deserialization

  • Built-in reference loop handling

  • Unity TextAsset support

  • JSON validation

  • Cancellation support

Requiring com.unity.nuget.newtonsoft-json 3.2.1 or above.


Json Converters

Followings data types of Json Converter are provided in AceLand.Library.Json.Converters, and used in JsonExtension by default.

  • AnimationCurve

  • Bounds

  • BoundsInt

  • Color

  • Gradient

  • Hash128

  • LayerMask

  • Matrix4x4

  • Quaternion

  • RectInt

  • Rect

  • Vector2

  • Vector2Int

  • Vector3

  • Vector3Int

  • Vector4


Create a Serializable Object for Newtonsoft.Json

using Newtonsoft.Json;

[Serializable, JsonObject(MemberSerialization.Fields)]
public class MyData
{
    public string publicForSerialize;

    [NonSerialized] 
    public string publicButNonSerialize;
    
    private string privateForNotSerialize;

    [SerializeField]
    private string privateButSerialize;
}

Serialization (Object to JSON)

// Convert object to JSON string
MyData data = new MyData();
string json = data.ToJson(cts.Token);

// Convert object to JSON string asynchronously
// for large scale of data
CancellationTokenSource cts = new CancellationTokenSource();
MyData data = new MyData();
string json = await data.ToJsonAsync(cts.Token);

// serialization with Type Name Handling for inherited object
string json = await data.ToJsonAsync(cts.Token, withTypeName: true);

Deserialization (JSON to Object)

// From string
string jsonString = "{\"name\":\"example\"}";
MyData data = jsonString.ToData<MyData>();

// From Unity TextAsset
public TextAsset jsonFile;
MyData data = jsonFile.ToData<MyData>();

// Convert JSON string to object asynchronously
// for large scale of data
// From string
string jsonString = "{\"name\":\"example\"}";
MyData data = await jsonString.ToDataAsync<MyData>(cts.Token);

// From Unity TextAsset
public TextAsset jsonFile;
MyData data = await jsonFile.ToDataAsync<MyData>(cts.Token);

// serialization with Type Name Handling for inherited object
string json = await jsonFile.ToDataAsync<MyData>(cts.Token, withTypeName: true);

JSON Validation

// Validate JSON string
string jsonString = "{\"name\":\"example\"}";
bool isValid = jsonString.IsValidJson();

// Validate Unity TextAsset
public TextAsset jsonFile;
bool isValid = jsonFile.IsValidJson();

Return false if jsonString is null.

Ruturn true if jsonString is empty or empty space only.

Error Handling

  • Serialization and deserialization operations include proper error handling

  • Detailed error messages include both operation type and data type information

  • Supports cancellation through CancellationToken

Best Practices

  • Always use cancellation tokens for long-running operations

  • Check JSON validity before deserialization in production code

  • Handle potential exceptions in async operations

  • Use TextAsset methods for Unity resource files


Using with Promise Awaiter

// Get application alive token from Promise
var token = Promise.ApplicationAliveToken;

// Serialization and Deserialization with Promise
string jsonString = "{\"name\":\"example\"}";
jsonString.ToData<MyData>(token )
    .Then(OnGetData)
    .Catch(Debug.LogError);

public TextAsset jsonFile;
jsonFile.ToData<MyData>(token, withTypeName: true)
    .Then(OnGetData)
    .Catch(Debug.LogError);

private void OnGetData(MyData data)
{
    // do stuff
}

Benefits of Promise Awaiter

  • Avoid async/await syntax complexity

  • Clean callback-based code structure

  • Better error handling chain

  • Easier to manage multiple asynchronous operations


Last updated 2 months ago

Please read for details of Promise.

Task Utils