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.

UnityEngine Types
Converter

AnimationCurve

AnimationCurveConverter

Bounds

BoundsConverter

BoundsInt

BoundsIntConverter

Color

ColorConverter

Gradient

GradientConverter

Hash128

Hash128Converter

LayerMask

LayerMaskConverter

Rect

RectConverter

RectInt

RectIntConverter

Vector2

Vector2Converter

Vector3

Vector3Converter

Vector4

Vector4Converter

Vector2Int

Vector2IntConverter

Vector3Int

Vector3IntConverter

Quaternion

QuaternionConverter

Matrix4x4

Matrix4x4Converter

Unity Native Types
Converter

float2

NativeFloat2Converter

float3

NativeFloat3Converter

float4

NativeFloat4Converter

quaternion

NativeQuaternionConverter

float2x2

NativeFloat2X2Converter

float2x3

NativeFloat2X3Converter

float2x4

NativeFloat2X4Converter

float3x2

NativeFloat3X2Converter

float3x3

NativeFloat3X3Converter

float3x4

NativeFloat3X4Converter

float4x2

NativeFloat4X2Converter

float4x3

NativeFloat4X3Converter

float4x4

NativeFloat4X4Converter


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;
    
    [JsonConverter(typeof(ColorConverter))]
    public Color color;
    
    [JsonConverter(typeof(GradientConverter))]
    public Gradient gradiant;
}

Serialization (Object to JSON)

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

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

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

Deserialization (JSON to Object)

// From string
JsonData jsonData = JsonData.Builder()
    .WithText("{\"name\":\"example\"}")
    .WithTypeName()
    .Build();
MyData data = jsonData .ToData<MyData>();

// From Unity TextAsset
public TextAsset jsonFile;
JsonData jsonData = JsonData.Builder()
    .WithText(jsonFile)
    .WithTypeName()
    .Build();
MyData data = jsonData.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