Files
Rhyculator/Assets/Script/MiniJson.cs
T
2026-10-24 11:55:22 +08:00

176 lines
6.6 KiB
C#

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
// 精簡 JSON 讀取器:物件 → Dictionary<string, object>、陣列 → List<object>、
// 數字 → double、字串 → string、true/false → bool、null → null
// 曲包譜面的 pos / path / end / locked 都是「可有可無」的欄位,JsonUtility 會把缺少的巢狀物件
// 填成預設值,分不出「沒有座標」和「座標 (0,0)」,所以自己解析
public static class MiniJson
{
public static object Parse(string json)
{
if (json == null) throw new FormatException("JSON 為空");
var p = new Parser(json);
p.SkipWhitespace();
object v = p.ParseValue();
p.SkipWhitespace();
if (!p.AtEnd) throw p.Error("結尾有多餘的內容");
return v;
}
public static Dictionary<string, object> AsObject(object v) => v as Dictionary<string, object>;
public static List<object> AsList(object v) => v as List<object>;
public static object Get(Dictionary<string, object> obj, string key)
=> obj != null && obj.TryGetValue(key, out var v) ? v : null;
public static string GetString(Dictionary<string, object> obj, string key, string fallback = null)
=> Get(obj, key) is string s ? s : fallback;
public static bool TryGetNumber(Dictionary<string, object> obj, string key, out double value)
{
if (Get(obj, key) is double d) { value = d; return true; }
value = 0;
return false;
}
public static double GetNumber(Dictionary<string, object> obj, string key, double fallback = 0)
=> TryGetNumber(obj, key, out var d) ? d : fallback;
public static int GetInt(Dictionary<string, object> obj, string key, int fallback = 0)
=> TryGetNumber(obj, key, out var d) ? (int)Math.Round(d) : fallback;
public static bool GetBool(Dictionary<string, object> obj, string key, bool fallback = false)
=> Get(obj, key) is bool b ? b : fallback;
private class Parser
{
private readonly string s;
private int i;
public Parser(string s) { this.s = s; }
public bool AtEnd => i >= s.Length;
public FormatException Error(string msg) => new FormatException($"JSON 第 {i} 個字元:{msg}");
public void SkipWhitespace()
{
while (i < s.Length && (s[i] == ' ' || s[i] == '\t' || s[i] == '\n' || s[i] == '\r')) i++;
}
public object ParseValue()
{
if (AtEnd) throw Error("內容不完整");
char c = s[i];
switch (c)
{
case '{': return ParseObject();
case '[': return ParseArray();
case '"': return ParseString();
case 't': Expect("true"); return true;
case 'f': Expect("false"); return false;
case 'n': Expect("null"); return null;
default:
if (c == '-' || (c >= '0' && c <= '9')) return ParseNumber();
throw Error($"無法解析 '{c}'");
}
}
private void Expect(string word)
{
if (string.CompareOrdinal(s, i, word, 0, word.Length) != 0) throw Error($"預期 {word}");
i += word.Length;
}
private Dictionary<string, object> ParseObject()
{
var obj = new Dictionary<string, object>();
i++; // {
SkipWhitespace();
if (i < s.Length && s[i] == '}') { i++; return obj; }
while (true)
{
SkipWhitespace();
if (AtEnd || s[i] != '"') throw Error("物件的鍵必須是字串");
string key = ParseString();
SkipWhitespace();
if (AtEnd || s[i] != ':') throw Error("缺少 ':'");
i++;
SkipWhitespace();
obj[key] = ParseValue();
SkipWhitespace();
if (AtEnd) throw Error("物件未結束");
if (s[i] == ',') { i++; continue; }
if (s[i] == '}') { i++; return obj; }
throw Error("物件內預期 ',' 或 '}'");
}
}
private List<object> ParseArray()
{
var list = new List<object>();
i++; // [
SkipWhitespace();
if (i < s.Length && s[i] == ']') { i++; return list; }
while (true)
{
SkipWhitespace();
list.Add(ParseValue());
SkipWhitespace();
if (AtEnd) throw Error("陣列未結束");
if (s[i] == ',') { i++; continue; }
if (s[i] == ']') { i++; return list; }
throw Error("陣列內預期 ',' 或 ']'");
}
}
private string ParseString()
{
i++; // 開頭的引號
var sb = new StringBuilder();
while (true)
{
if (AtEnd) throw Error("字串未結束");
char c = s[i++];
if (c == '"') return sb.ToString();
if (c != '\\') { sb.Append(c); continue; }
if (AtEnd) throw Error("字串未結束");
char e = s[i++];
switch (e)
{
case '"': sb.Append('"'); break;
case '\\': sb.Append('\\'); break;
case '/': sb.Append('/'); break;
case 'b': sb.Append('\b'); break;
case 'f': sb.Append('\f'); break;
case 'n': sb.Append('\n'); break;
case 'r': sb.Append('\r'); break;
case 't': sb.Append('\t'); break;
case 'u':
if (i + 4 > s.Length) throw Error("\\u 跳脫不完整");
sb.Append((char)int.Parse(s.Substring(i, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture));
i += 4;
break;
default: throw Error($"不支援的跳脫 \\{e}");
}
}
}
private double ParseNumber()
{
int start = i;
if (s[i] == '-') i++;
while (i < s.Length && IsNumberChar(s[i])) i++;
string token = s.Substring(start, i - start);
if (!double.TryParse(token, NumberStyles.Float, CultureInfo.InvariantCulture, out double d))
throw Error($"數字格式錯誤 '{token}'");
return d;
}
private static bool IsNumberChar(char c)
=> (c >= '0' && c <= '9') || c == '.' || c == 'e' || c == 'E' || c == '+' || c == '-';
}
}