CypherPotato.LightJson 0.14.4

dotnet add package CypherPotato.LightJson --version 0.14.4
                    
NuGet\Install-Package CypherPotato.LightJson -Version 0.14.4
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="CypherPotato.LightJson" Version="0.14.4" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="CypherPotato.LightJson" Version="0.14.4" />
                    
Directory.Packages.props
<PackageReference Include="CypherPotato.LightJson" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add CypherPotato.LightJson --version 0.14.4
                    
#r "nuget: CypherPotato.LightJson, 0.14.4"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package CypherPotato.LightJson@0.14.4
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=CypherPotato.LightJson&version=0.14.4
                    
Install as a Cake Addin
#tool nuget:?package=CypherPotato.LightJson&version=0.14.4
                    
Install as a Cake Tool

LightJson

This project was based in the awesome work of LightJson, originally made by Marcos Lopez C.

This fork includes some personal tweaks. It is a JSON library focused on not using reflection, where object mapping is made manually and requires mapping to serialize/deserialize typed JSON messages.

Almost everything in this class is inherited from the main project mentioned above, with new features:

  • Unlike the original project, a JsonValue does not contain any As[Type] properties, but has a method for each JSON type, like GetString() or even GetNumber(), and the main difference is that you cannot get an implicit value of what the JsonValue is. For example, you cannot read JsonValue.GetBoolean() if the stored value is a string, even if it's value is "true" or 0.
  • All functions that return an object converted from a JsonValue, such as JsonValue.GetString() for example, do not return nullable values, neither accepts it. You can check for nullable JSON values using JsonValue.MaybeNull(). Null values would throw an exception if not used with MaybeNull().
  • Added JsonOptions, which contains:
    • PropertyNameComparer, which sets the default string comparer used for comparing property names and constructor parameters names.
    • Converters, which aims to manage JSON converters.
    • NamingPolicy, which transforms the property name of a JSON object on the JSON output.
    • WriteIndented, which sets whether the JSON serializer should write indentend, pretty formatted, output.
    • StringEncoder, which sets the encoder used for escaping strings.
    • ThrowOnDuplicateObjectKeys, which sets an boolean indicating where the JSON parser should throw on duplicated object keys.
    • DynamicObjectMaxDepth, sets the maximum depth for serializing or deserializing objects.
    • AllowNumbersAsStrings, sets whether the JSON deserializer should allow parsing string JSON values into numeric types.
    • SerializationFlags, which allows to pass JsonSerializationFlags flags to the JSON serializer/deserializer, such as the JSON5 deserializer.
    • InfinityHandler which sets the output for the JSON writer when writing double Infinity numbers.
    • SerializerContext which allows you to specify an IJsonTypeInfoResolver used for serialization and deserialization of dynamic objects.
  • Experimental JSON5 support with SerializationFlags.All.
  • Undefined values, as it is, values which aren't defined or does not exist in the parent object/array, will come with JsonValueType.Undefined type instead of JsonValueType.Null.
  • This projects targets .NET 6 and above.
  • Experimental support for including the JSON value path into error messages.
  • Source generation support through SerializerContext.

Serialize and deserialize data

All serialized or deserialized information results in the JsonValue structure. From this object, you can manipulate the JSON document. In the examples below, we will show how serialization and deserialization works.

// serialize primitive values
json = new JsonValue("hello").ToString();
Console.WriteLine(json); // "hello"

// serialize complex objects
json = JsonOptions.Default.Serialize(new { prop1 = "hello", prop2 = "world" }).ToString();
Console.WriteLine(json); // {"prop1":"hello","prop2":"world"}

// for custom types, an converter must be defined in the JsonOptions.Converters
json = JsonOptions.Default.Serialize(Guid.NewGuid()).ToString();
Console.WriteLine(json); // "9d282aa8-9385-4158-a094-55a01a39feae"

// deserialize primitive values
json = """
    {
        "number": 12.52,
        "name": "John Lennon",
        "arrayOfInts": [ 20, 30, 40 ],
        "object": {
            "guid": "9d282aa8-9385-4158-a094-55a01a39feae"
        }
    }
    """;

var objJson = JsonOptions.Default.Deserialize(json);
        
// implicitly converts the JsonValue into an JsonObject when acessing
// through key value
double objNumber = objJson["number"].GetNumber();

// MaybeNull() indicates that the value at $.name can be null
string? name = objJson["name"].MaybeNull()?.GetString();

// gets $.arrayOfInts[1] as integer. it must be an non-null number
int intAtIndex1 = objJson["arrayOfInts"][1].GetInteger();

// explicitly gets an Guid from $.object.guid
Guid convertedValue = objJson["object"]["guid"].Get<Guid>();

JSON converters

Here's an example of an System.DateTime converter, which serializes and deserializes values into it:

static void Main(string[] args)
{
    JsonOptions.Default.Converters.Add(new DateTimeConverter());
    string json = JsonOptions.Default.SerializeJson(DateTime.Now);    
    Console.WriteLine(json);
}

public sealed class DateTimeConverter : JsonConverter
{
	public override Boolean CanSerialize(Type type, JsonOptions currentOptions)
	{
		return type == typeof(DateTime);
	}
	
	public override Object Deserialize(JsonValue value, Type requestedType, JsonOptions currentOptions)
	{
		return DateTime.Parse(value.GetString());
	}
	
	public override JsonValue Serialize(Object value, JsonOptions currentOptions)
	{
		return new JsonValue(t.ToString("s"));
	}
}

These types already has converters defined for them:

  • Char
  • DateOnly
  • DateTime
  • Enums
  • Guid
  • IpAddress
  • TimeOnly
  • TimeSpan
  • Uri
  • Dictionaries (only classes which inherits IDictionary and IDictionary<string, object? are supported)

Fluent syntax for retrieving items

string json = """
    {
        "foobar": "hello",
        "bazdaz": null,
        "duzkaz": [
            "foo",
            "bar",
            "daz"
        ],
        "user": {
            "name": "John McAffee", "age": 52
        }
    }
    """;

var obj = JsonOptions.Default.Deserialize(json);

// $.foobar must be present, non null and carry an string value.
string stringValue = obj["foobar"].GetString();

// $.bazdaz can be null or undefined, but if not, it must be an string.
string? optionalValue = obj["bazdaz"].MaybeNull()?.GetString();

// $.duzkaz must be present, non null, be an json array and every children on it
// must be an string value.
string[] arrayItems = obj["duzkaz"].GetJsonArray().Select(i => i.GetString()).ToArray();
// or
string[] arrayItems = obj["duzkaz"].GetJsonArray().ToArray<string>();
// or
IEnumerable<string> arrayItems = obj["duzkaz"].GetJsonArray().EveryAs<string>();
// or
IEnumerable<string?> arrayItems = obj["duzkaz"].GetJsonArray().EveryAsNullable<string>();

// $.user must be present, non null, and must be converted to the User type, which it's converter
// is defined on JsonOptions.Converters.
User user = obj["user"].Get<User>();
// nullable
User? user = obj["user"].MaybeNull()?.Get<User>();

System.Text.Json interop

This library can be used in conjunction with the native System.Text.Json of .NET. Most of the JSON functions of .NET can be used with LightJson, including attributes, type infos and serialize json value.

JsonArray arr = new JsonArray(JsonOptions.Default, "hello", "world");

string jsonEncoded = JsonSerializer.Serialize(arr);
Console.WriteLine(jsonEncoded); // {"foo": "bar"}
Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (2)

Showing the top 2 NuGet packages that depend on CypherPotato.LightJson:

Package Downloads
Sisk.JsonRpc

This package provides an JSON-RPC 2.0 interface for Sisk projects.

Sisk.ModelContextProtocol

This package provides an implementation of the MCP (Model Context Protocol) protocol for the Sisk Framework.

GitHub repositories (1)

Showing the top 1 popular GitHub repositories that depend on CypherPotato.LightJson:

Repository Stars
sisk-http/core
Sisk's request and response processor mainframe source code.
Version Downloads Last Updated
0.14.4 156 10/8/2025
0.14.3 157 10/7/2025
0.14.2 160 9/8/2025
0.14.1 168 9/2/2025
0.14.0 128 7/30/2025
0.14.0-beta8 340 7/25/2025
0.14.0-beta7 296 6/11/2025
0.14.0-beta6 164 6/4/2025
0.14.0-beta4 226 4/17/2025
0.14.0-beta3 194 4/13/2025
0.14.0-beta2 206 4/13/2025
0.14.0-beta1 185 4/10/2025
0.13.1 158 2/17/2025
0.13.0 143 12/16/2024
0.12.0 142 12/11/2024
0.11.0 142 11/11/2024
0.10.7 121 10/25/2024
0.10.6 152 10/10/2024
0.10.5 155 9/30/2024
0.10.4 133 9/26/2024
0.10.3 137 9/26/2024
0.10.1 152 8/30/2024
0.10.0-beta4 127 8/27/2024
0.10.0-beta3 137 8/26/2024
0.10.0-beta1 151 8/23/2024
0.9.3 173 7/18/2024
0.9.2 174 7/3/2024
0.9.1 163 7/1/2024
0.9.0 146 5/28/2024
0.9.0-beta3 130 5/14/2024
0.9.0-beta2 144 5/4/2024
0.9.0-beta1 97 5/2/2024
0.8.0 169 4/4/2024
0.7.0 155 3/24/2024
0.6.0 182 1/18/2024
0.5.6 235 12/6/2023
0.5.5 187 11/30/2023