codeAPI Reference

Sandbox.Json

calendar_today May 3, 2026 schedule ~1 min read person patrickjr verified 50

Sandbox.Json

JSON serialization utilities.

Overview

Json provides methods for serializing objects to JSON and parsing JSON strings.

Serialize

CSHARP
// Object to JSON string
string json = Json.Serialize(myObject);

// With options
string json = Json.Serialize(myObject, new JsonSerializerOptions
{
    WriteIndented = true
});

Deserialize

CSHARP
// JSON to object
MyClass obj = Json.Deserialize<MyClass>(jsonString);

// Anonymous
var data = Json.Deserialize<Dictionary<string, object>>(json);

Parse

CSHARP
// Parse JSON
var doc = JsonDocument.Parse(jsonString);

// Access properties
string name = doc.RootElement.GetProperty("name").GetString();
int score = doc.RootElement.GetProperty("score").GetInt32();

To Node

CSHARP
// Convert to JsonNode for manipulation
JsonNode node = JsonNode.Parse(json);

// Modify
node["name"] = "New Name";
node["score"] = 100;

// Back to string
string newJson = node.ToJsonString();

Common Uses

CSHARP
// Save data
var saveData = new { Level = 5, Health = 100, Position = WorldPosition };
string json = Json.Serialize(saveData);
Storage.SetString("save", json);

// Load data
string json = Storage.GetString("save");
var data = Json.Deserialize<SaveData>(json);

Custom Serialization

CSHARP
[Serializable]
public class PlayerData
{
    public string Name { get; set; }
    public int Score { get; set; }
    
    [JsonIgnore] // Don't serialize
    public float TemporaryValue { get; set; }
}

Error Handling

CSHARP
try
{
    var obj = Json.Deserialize<MyClass>(json);
}
catch (JsonException ex)
{
    Log.Error($"Failed to parse JSON: {ex.Message}");
}
Was this helpful?