A robust JSON parser implementation in C# that can parse, manipulate, and serialize JSON data. This implementation follows JSON specification standards and provides comprehensive error handling.
- Lexical Analysis: Converts JSON text into tokens
- Parsing: Builds an abstract syntax tree from tokens
- Serialization: Converts JSON objects back to string format
- Support for all JSON data types:
- Objects
- Arrays
- Strings (with escape sequences)
- Numbers
- Booleans
- Null values
- .NET 8.0 SDK or later
- A terminal/command prompt
- Clone the repository
- Navigate to the project directory
- Run the following command to build:
dotnet build
After building, you can run the program using:
dotnet run
The program includes a sample JSON string that will be parsed and serialized to demonstrate the functionality.
The project includes test files that can be run using:
dotnet test
- Tokenizes input JSON string
- Handles whitespace and special characters
- Supports escape sequences in strings
- Validates numeric formats
- Recognizes keywords (true, false, null)
- Constructs JSON object model from tokens
- Implements recursive descent parsing
- Handles nested structures
- Provides detailed error messages for invalid JSON
JsonValue
: Base abstract class for all JSON valuesJsonObject
: Represents JSON objects with key-value pairsJsonArray
: Represents JSON arraysJsonPrimitive
: Represents primitive values (strings, numbers, booleans, null)
- Converts JSON objects back to string format
- Properly escapes special characters
- Maintains formatting consistency
string json = "{ \"name\": \"John\", \"age\": 30, \"isStudent\": false }";
// Tokenize
var lexer = new JsonLexer(json);
var tokens = lexer.Tokenize();
// Parse
var parser = new JsonParser(tokens);
var jsonObject = parser.Parse();
// Serialize back to string
var serializer = new JsonSerializer();
string jsonString = serializer.Serialize(jsonObject);
The parser includes comprehensive error handling for:
- Malformed JSON
- Invalid tokens
- Unexpected characters
- Unterminated strings
- Invalid escape sequences
- Improper nesting of objects and arrays
The project includes test files for:
- Lexer testing (
JsonLexerTests.cs
) - Parser testing (
JsonParserTests.cs
) - Serializer testing (
JsonSerializerTests.cs
)
The parser is implemented using a recursive descent approach, which makes it easy to understand and maintain. It processes JSON input in three main stages:
- Lexical Analysis: Converts the input string into a sequence of tokens
- Parsing: Converts the tokens into a tree structure
- Serialization: Converts the tree structure back into a JSON string
The implementation follows best practices for error handling and provides detailed error messages to help with debugging.