在 C# 中构建双向 TOON 解析器:轻松转换 TOON JSON

发布: (2025年12月8日 GMT+8 16:49)
4 min read
原文: Dev.to

Source: Dev.to

介绍

Toon(Token‑Oriented Object Notation)是一种新近推广的格式,专门用于保存 LLM token。
它体积小、可读性强、极其轻量,并针对每个 token 都至关重要的 AI 工作流进行了优化。

与 JSON 相比,TOON 减少了噪音,避免了不必要的花括号/引号,并以扁平且 token‑高效的方式存储结构化数据。随着 AI 提示和基于代理的架构的兴起,TOON 正迅速成为开发者和机器学习工程师的最爱。

在本指南中,你将学习如何在 C# 中构建一个完整的双向 TOON 解析器:

  • TOON → JSON
  • JSON → TOON
  • 完全自动、可扩展且易于扩展

该方案兼容 .NET 6、.NET 8 和 .NET 9,且无需外部依赖。

步骤 1:创建 ToonConverter

我们将构建一个实用类,包含:

  • ParseToon() – 将 TOON 转换为 C# 字典
  • ToonToJson() – 将 TOON 转换为 JSON
  • JsonToToon() – 将 JSON 再转回 TOON

新建一个文件 ToonConverter.cs,并粘贴以下代码:

using System.Text.Json;
using System.Text.Json.Nodes;

public static class ToonConverter
{
    // --------------------------------------
    // 1. TOON → OBJECT (Dictionary)
    // --------------------------------------
    public static Dictionary>> ParseToon(string toon)
    {
        var result = new Dictionary>>();
        var lines = toon.Split('\n', StringSplitOptions.RemoveEmptyEntries)
                        .Select(x => x.Trim()).ToList();

        int i = 0;

        while (i  f.Trim()).ToArray();

            var rows = new List>();

            while (i  v.Trim()).ToArray();

                var obj = new Dictionary();
                for (int f = 0; f  x.Key).ToList();

            sb.Append($"{name}[{arr.Count}]{{");
            sb.Append(string.Join(",", fields));
            sb.AppendLine("}:");

            // Add rows
            foreach (JsonNode? row in arr)
            {
                var obj = row!.AsObject();
                sb.AppendLine(string.Join(",", fields.Select(f => obj[f]!.ToString())));
            }

            sb.AppendLine();
        }

        return sb.ToString().Trim();
    }
}

步骤 2:尝试 TOON → JSON 转换

示例 TOON 格式

Characters[3]{Name,Age,Role}:
Alice,25,Warrior
Bob,30,Mage
Charlie,22,Rogue

Items[2]{ItemName,Quantity,Price}:
Sword,5,100
Potion,20,10

转换代码

string toonData = @"
 Characters[3]{Name,Age,Role}:
 Alice,25,Warrior
 Bob,30,Mage
 Charlie,22,Rogue

 Items[2]{ItemName,Quantity,Price}:
 Sword,5,100
 Potion,20,10
";

string json = ToonConverter.ToonToJson(toonData);
Console.WriteLine(json);

输出

TOON to JSON result

Formatted JSON

JSON 结构清晰、整洁,已可直接用于 API 或存储。

步骤 3:JSON → TOON 转换

给定的 JSON

{
  "Characters": [
    {
      "Name": "Alice",
      "Age": "25",
      "Role": "Warrior"
    },
    {
      "Name": "Bob",
      "Age": "30",
      "Role": "Mage"
    },
    {
      "Name": "Charlie",
      "Age": "22",
      "Role": "Rogue"
    }
  ],
  "Items": [
    {
      "ItemName": "Sword",
      "Quantity": "5",
      "Price": "100"
    },
    {
      "ItemName": "Potion",
      "Quantity": "20",
      "Price": "10"
    }
  ]
}

转回 TOON

string toonFromJson = ToonConverter.JsonToToon(json);
Console.WriteLine(toonFromJson);

输出

JSON to TOON result

往返转换顺利完成。

步骤 4:集成到你的项目中

该解析器非常适用于:

  • AI 代理
  • LLM 提示优化
  • 内存高效的数据传输
  • 基于聊天的结构化数据
  • 内部 DSL
  • AI 工作流的配置文件

由于 TOON 极其小巧,你的提示保持简洁且对 token 友好。

总结

本文我们介绍了如何:

  • 创建一个轻量级的双向 TOON 解析器
  • 实现 TOON → JSON
  • 实现 JSON → TOON
  • 处理多块、多行的结构化数据

TOON 正快速成为 AI 时代的 JSON 替代品,拥有自己的解析器可以为未来的工作流提供最大灵活性。

Back to Blog

相关文章

阅读更多 »