Development of this project is entirely funded by the community. Consider donating to support! |
QuickJson is a very basic JSON parser, distributed as a source-only package that can be referenced without imposing any run-time dependencies.
Terms of use[?]
By using this project or its source code, for any purpose and in any shape or form, you grant your implicit agreement to all the following statements:
- You condemn Russia and its military aggression against Ukraine
- You recognize that Russia is an occupant that unlawfully invaded a sovereign state
- You support Ukraine's territorial integrity, including its claims over temporarily occupied territories of Crimea and Donbas
- You reject false narratives perpetuated by Russian state propaganda
To learn more about the war and how you can help, click here. Glory to Ukraine! 🇺🇦
- 📦 NuGet:
dotnet add package QuickJson
Warning: To use this package, your project needs to target C# 10 or later. You can ensure this by setting
<LangVersion>latest</LangVersion>
in the project file.
To parse a JSON string, call Json.TryParse(...)
or Json.Parse(...)
:
// This returns null on invalid JSON
var json = Json.TryParse(
"""
{
"foo": [
69,
true,
"bar"
]
}
"""
);
// This throws on invalid JSON
var json = Json.Parse("...");
To retrieve a nested node in the parsed JSON, use [Try]GetChild(...)
:
// May return null if the property doesn't exist
// or if the referenced node is not an object
var foo = json.TryGetChild("foo");
// May return null if the child doesn't exist
// or if the referenced node is not an array
var child1 = foo?.TryGetChild(0);
var child2 = foo?.TryGetChild(1);
var child3 = foo?.TryGetChild(2);
Alternatively, you can also enumerate all object properties using EnumerateProperties()
or all array children using EnumerateChildren()
:
// Returns an empty enumerator if the referenced node is not an object
foreach (var prop in json.EnumerateProperties())
{
var name = prop.Name; // string
var value = prop.Value; // JsonNode
// ...
}
// Returns an empty enumerator if the referenced node is not an array
foreach (var child in json.EnumerateChildren())
{
// ...
}
In order to extract values from nodes, use [Try]GetNumber()
, [Try]GetBool()
, or [Try]GetString()
:
// May return null if the node contains a value of a different kind
var value1 = child1?.TryGetNumber(); // double
var value2 = child2?.TryGetBool(); // bool
var value3 = child3?.TryGetString(); // string