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


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

Please read Task Utils for details of Promise.


Last updated