Skip to content

[API Proposal]: Add BigInteger support to System.Text.Json #60780

@eiriktsarpalis

Description

@eiriktsarpalis

Background and motivation

Currently System.Text.Json has no support for serializing BigInteger values. This is a proposal for serializing BigInteger values as arbitrarily sized JSON numbers.

API Proposal

namespace System.Text.Json
{
    public ref partial struct Utf8JsonReader
    {
+        public BigInteger GetBigInteger();
+        public bool TryGetBigInteger(out BigInteger value);
    }

    public sealed partial class Utf8JsonWriter
    {
+        public void WriteNumber(JsonEncodedText propertyName, BigInteger value);
+        public void WriteNumber(string propertyName, BigInteger value);
+        public void WriteNumber(ReadOnlySpan<char> propertyName, BigInteger value);
+        public void WriteNumber(ReadOnlySpan<byte> utf8PropertyName, BigInteger value);
+        public void WriteNumberValue(BigInteger value);
    }

    public readonly partial struct JsonElement
    {
+        public BigInteger GetBigInteger();
+        public bool TryGetBigInteger(out BigInteger value)
    }
}

namespace System.Text.Json.Node
{
    public abstract partial class JsonNode
    {
+        public static explicit operator BigInteger(JsonNode value);
+        public static explicit operator BigInteger?(JsonNode? value);
+        public static implicit operator JsonNode(BigInteger value);
+        public static implicit operator JsonNode?(BigInteger? value);
    }
}

namespace System.Text.Json.Serialization.Metadata
{
    public static partial class JsonMetadataServices
    {
+        public static JsonConverter<BigInteger> BigIntegerConverter { get; }
    }
}

API Usage

JsonSerializer.Serialize((BigInteger)42);

// Current JSON: {"IsPowerOfTwo":false,"IsZero":false,"IsOne":false,"IsEven":true,"Sign":1}
// New JSON: 42

Alternative Designs

No response

Risks

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionEarly API idea and discussion, it is NOT ready for implementationarea-System.Text.JsonwishlistIssue we would like to prioritize, but we can't commit we will get to it yet

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions