基于json语法树,流式解析json的c#方法
- User
基于json语法树,流式解析json的c#方法
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
基于json语法树,流式解析json的c#方法
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
基于JSON语法树的流式解析可以通过构建状态机来实现。以下是一个C#实现方案:
流式JSON解析器通过维护一个解析状态栈,逐字符处理输入流,根据当前状态和输入字符决定状态转换和语法树节点的创建。
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
public enum JsonTokenType
{
ObjectStart, ObjectEnd, ArrayStart, ArrayEnd,
String, Number, Boolean, Null, Colon, Comma, EOF
}
public class JsonToken
{
public JsonTokenType Type { get; set; }
public string Value { get; set; }
public int Position { get; set; }
}
public abstract class JsonNode
{
public abstract void Accept(IJsonVisitor visitor);
}
public class JsonObject : JsonNode
{
public Dictionary<string, JsonNode> Properties { get; } = new();
public override void Accept(IJsonVisitor visitor) => visitor.Visit(this);
}
public class JsonArray : JsonNode
{
public List<JsonNode> Elements { get; } = new();
public override void Accept(IJsonVisitor visitor) => visitor.Visit(this);
}
public class JsonValue : JsonNode
{
public object Value { get; set; }
public override void Accept(IJsonVisitor visitor) => visitor.Visit(this);
}
public interface IJsonVisitor
{
void Visit(JsonObject obj);
void Visit(JsonArray array);
void Visit(JsonValue value);
}
public class StreamingJsonParser
{
private readonly TextReader _reader;
private int _position;
private char _currentChar;
private bool _hasChar;
public StreamingJsonParser(TextReader reader)
{
_reader = reader;
NextChar();
}
private void NextChar()
{
int ch = _reader.Read();
if (ch == -1)
{
_hasChar = false;
_currentChar = '\0';
}
else
{
_hasChar = true;
_currentChar = (char)ch;
_position++;
}
}
private void SkipWhitespace()
{
while (_hasChar && char.IsWhiteSpace(_currentChar))
NextChar();
}
public JsonNode Parse()
{
SkipWhitespace();
return ParseValue();
}
private JsonNode ParseValue()
{
SkipWhitespace();
if (!_hasChar)
throw new InvalidOperationException("Unexpected end of input");
return _currentChar switch
{
'{' => ParseObject(),
'[' => ParseArray(),
'"' => new JsonValue { Value = ParseString() },
't' or 'f' => new JsonValue { Value = ParseBoolean() },
'n' => ParseNull(),
_ when char.IsDigit(_currentChar) || _currentChar == '-' =>
new JsonValue { Value = ParseNumber() },
_ => throw new InvalidOperationException($"Unexpected character: {_currentChar}")
};
}
private JsonObject ParseObject()
{
var obj = new JsonObject();
NextChar(); // skip '{'
SkipWhitespace();
if (_hasChar && _currentChar == '}')
{
NextChar();
return obj;
}
while (_hasChar)
{
SkipWhitespace();
// Parse property name
if (_currentChar != '"')
throw new InvalidOperationException("Expected property name");
string propertyName = ParseString();
SkipWhitespace();
// Expect colon
if (!_hasChar || _currentChar != ':')
throw new InvalidOperationException("Expected ':'");
NextChar(); // skip ':'
SkipWhitespace();
// Parse property value
JsonNode value = ParseValue();
obj.Properties[propertyName] = value;
SkipWhitespace();
if (!_hasChar)
throw new InvalidOperationException("Unexpected end of input");
if (_currentChar == '}')
{
NextChar();
break;
}
if (_currentChar == ',')
{
NextChar();
continue;
}
throw new InvalidOperationException($"Expected ',' or '}}', got '{_currentChar}'");
}
return obj;
}
private JsonArray ParseArray()
{
var array = new JsonArray();
NextChar(); // skip '['
SkipWhitespace();
if (_hasChar && _currentChar == ']')
{
NextChar();
return array;
}
while (_hasChar)
{
JsonNode element = ParseValue();
array.Elements.Add(element);
SkipWhitespace();
if (!_hasChar)
throw new InvalidOperationException("Unexpected end of input");
if (_currentChar == ']')
{
NextChar();
break;
}
if (_currentChar == ',')
{
NextChar();
SkipWhitespace();
continue;
}
throw new InvalidOperationException($"Expected ',' or ']', got '{_currentChar}'");
}
return array;
}
private string ParseString()
{
var sb = new StringBuilder();
NextChar(); // skip opening quote
while (_hasChar && _currentChar != '"')
{
if (_currentChar == '\\')
{
NextChar();
if (!_hasChar)
throw new InvalidOperationException("Unexpected end of input in string");
sb.Append(_currentChar switch
{
'"' => '"',
'\\' => '\\',
'/' => '/',
'b' => '\b',
'f' => '\f',
'n' => '\n',
'r' => '\r',
't' => '\t',
'u' => ParseUnicodeEscape(),
_ => throw new InvalidOperationException($"Invalid escape sequence: \\{_currentChar}")
});
}
else
{
sb.Append(_currentChar);
}
NextChar();
}
if (!_hasChar || _currentChar != '"')
throw new InvalidOperationException("Unterminated string");
NextChar(); // skip closing quote
return sb.ToString();
}
private char ParseUnicodeEscape()
{
int code = 0;
for (int i = 0; i < 4; i++)
{
NextChar();
if (!_hasChar || !IsHexDigit(_currentChar))
throw new InvalidOperationException("Invalid unicode escape sequence");
code = code * 16 + GetHexValue(_currentChar);
}
return (char)code;
}
private bool IsHexDigit(char c) =>
char.IsDigit(c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
private int GetHexValue(char c) => c switch
{
>= '0' and <= '9' => c - '0',
>= 'a' and <= 'f' => c - 'a' + 10,
>= 'A' and <= 'F' => c - 'A' + 10,
_ => throw new ArgumentException("Invalid hex character")
};
private double ParseNumber()
{
var sb = new StringBuilder();
if (_currentChar == '-')
{
sb.Append(_currentChar);
NextChar();
}
if (!_hasChar || !char.IsDigit(_currentChar))
throw new InvalidOperationException("Invalid number format");
// Parse integer part
if (_currentChar == '0')
{
sb.Append(_currentChar);
NextChar();
}
else
{
while (_hasChar && char.IsDigit(_currentChar))
{
sb.Append(_currentChar);
NextChar();
}
}
// Parse decimal part
if (_hasChar && _currentChar == '.')
{
sb.Append(_currentChar);
NextChar();
if (!_hasChar || !char.IsDigit(_currentChar))
throw new InvalidOperationException("Invalid number format");
while (_hasChar && char.IsDigit(_currentChar))
{
sb.Append(_currentChar);
NextChar();
}
}
// Parse exponent
if (_hasChar && (_currentChar == 'e' || _currentChar == 'E'))
{
sb.Append(_currentChar);
NextChar();
if (_hasChar && (_currentChar == '+' || _currentChar == '-'))
{
sb.Append(_currentChar);
NextChar();
}
if (!_hasChar || !char.IsDigit(_currentChar))
throw new InvalidOperationException("Invalid number format");
while (_hasChar && char.IsDigit(_currentChar))
{
sb.Append(_currentChar);
NextChar();
}
}
return double.Parse(sb.ToString());
}
private bool ParseBoolean()
{
if (_currentChar == 't')
{
ExpectString("true");
return true;
}
else if (_currentChar == 'f')
{
ExpectString("false");
return false;
}
throw new InvalidOperationException("Invalid boolean value");
}
private JsonValue ParseNull()
{
ExpectString("null");
return new JsonValue { Value = null };
}
private void ExpectString(string expected)
{
foreach (char c in expected)
{
if (!_hasChar || _currentChar != c)
throw new InvalidOperationException($"Expected '{expected}'");
NextChar();
}
}
}
// 使用示例
string json = """{"name": "John", "age": 30, "items": [1, 2, 3]}""";
using var reader = new StringReader(json);
var parser = new StreamingJsonParser(reader);
JsonNode root = parser.Parse();
// 实现访问者模式来处理解析结果
public class JsonPrinter : IJsonVisitor
{
private int _indent = 0;
public void Visit(JsonObject obj)
{
Console.WriteLine("{");
_indent++;
bool first = true;
foreach (var kvp in obj.Properties)
{
if (!first) Console.WriteLine(",");
Console.Write($"{new string(' ', _indent * 2)}\"{kvp.Key}\": ");
kvp.Value.Accept(this);
first = false;
}
_indent--;
Console.WriteLine($"\n{new string(' ', _indent * 2)}}}");
}
public void Visit(JsonArray array)
{
Console.WriteLine("[");
_indent++;
for (int i = 0; i < array.Elements.Count; i++)
{
if (i > 0) Console.WriteLine(",");
Console.Write(new string(' ', _indent * 2));
array.Elements[i].Accept(this);
}
_indent--;
Console.WriteLine($"\n{new string(' ', _indent * 2)}]");
}
public void Visit(JsonValue value)
{
if (value.Value is string s)
Console.Write($"\"{s}\"");
else if (value.Value == null)
Console.Write("null");
else
Console.Write(value.Value);
}
}
// 使用
var printer = new JsonPrinter();
root.Accept(printer);
这个实现提供了完整的流式JSON解析功能,支持所有标准JSON语法,并通过语法树结构和访问者模式提供了灵活的数据处理方式。解析器逐字符读取输入,内存占用相对较小,适合处理大型JSON文件。