How to Keep Raw JSON in a Property with JsonElement in C#
Declare a property as JsonElement, as in record Setting(string Name, JsonElement Value), and System.Text.Json keeps whatever JSON that property holds, whether a number, a string or a whole object, and writes it back out unchanged. Your code doesn't need a class for its shape.
Microsoft's reference for the type: Represents a specific JSON value within a JsonDocument.
As a property, it takes any kind of JSON value. The System.Text.Json guide suggests it for a property whose JSON varies: If you just want to be flexible about what JSON is acceptable for a particular property, an alternative is to deserialize into JsonElement or JsonNode. Any valid JSON property can be deserialized into JsonElement or JsonNode.
Syntax
using System.Text.Json;
record <Record>(<Type> <Property>, JsonElement <RawProperty>);
class <Class>
{
public JsonElement <RawProperty> { get; set; }
}
| Part | What it is |
|---|---|
using System.Text.Json; | The namespace JsonElement is in |
JsonElement <RawProperty> | The property that keeps a piece of JSON: an object, an array, a string, a number, true, false or null |
<Record> or <Class> | The type you serialize. Its other properties are ordinary ones |
Both forms work: a positional record's parameter becomes a property, and a class declares the property itself.
The Example
A console app called RawJsonProperty reads an app's settings from JSON. Each setting has a name and a value, and the values are different kinds of JSON: the number 7 for the volume, the string "dark" for the theme, and an object with a width and a height for the window. A Setting record keeps each value in a JsonElement property, and the app writes the settings back as JSON.
Prerequisites
- The .NET 10 SDK.
dotnet --versionprints a version that starts with10.0.
Step 1: Create a Console App
dotnet new console -n RawJsonProperty
cd RawJsonProperty
The template "Console App" was created successfully.
Processing post-creation actions...
Restoring /Users/you/source/RawJsonProperty/RawJsonProperty.csproj:
Determining projects to restore...
Restored /Users/you/source/RawJsonProperty/RawJsonProperty.csproj (in 43 ms).
Restore succeeded.
dotnet new console -n RawJsonProperty creates a folder named RawJsonProperty with a project file and a Program.cs, and cd moves into it. Everything this example uses is part of .NET, so there's no package to add. Open the folder in VS Code, or RawJsonProperty.csproj in Visual Studio.
Step 2: Write the Code
Replace everything in Program.cs. The record goes at the end of the file:
// A setting's name, and its value as a piece of JSON of any kind.
record Setting(string Name, JsonElement Value);
Setting is a positional record: Name is an ordinary string, and Value is a JsonElement, so it can hold any kind of JSON.
At the top of the file, the settings as JSON, read into Setting records:
using System.Text.Json;
// Settings from a file. Each value is a different kind of JSON.
string json = """[{"Name":"volume","Value":7},{"Name":"theme","Value":"dark"},{"Name":"window","Value":{"Width":800,"Height":600}}]""";
// Read: each Value keeps its piece of JSON as it is.
List<Setting> settings = JsonSerializer.Deserialize<List<Setting>>(json)!;
foreach (Setting setting in settings)
{
Console.WriteLine($"{setting.Name}: {setting.Value.ValueKind}, {setting.Value.GetRawText()}");
}
json is a raw string literal: everything between the two """ is text, so the quotes inside need no escaping. JsonSerializer.Deserialize<List<Setting>> reads the JSON array into a list of records, and each Value gets its own piece of JSON. ValueKind says what kind of JSON it is, and GetRawText() gives it back as text. Their references: Gets the type of the current JSON value. and Gets a string that represents the original input data backing this value.
Then write them back:
// Write: the same pieces of JSON go back out unchanged.
string written = JsonSerializer.Serialize(settings);
Console.WriteLine(written);
Console.WriteLine($"Same as the file: {written == json}");
JsonSerializer.Serialize(settings) turns the list back into JSON, and written == json compares it with the text the program started from.
Step 3: Run It
Run it in VS Code's terminal, or press Ctrl+F5 in Visual Studio:
dotnet run
volume: Number, 7
theme: String, "dark"
window: Object, {"Width":800,"Height":600}
[{"Name":"volume","Value":7},{"Name":"theme","Value":"dark"},{"Name":"window","Value":{"Width":800,"Height":600}}]
Same as the file: True

- Reading: each
Valueholds its own kind of JSON, aNumber, aStringand anObject, with the window'sWidthof 800 andHeightof 600 inside it. No class describes the window. - Writing: the settings went back out as exactly the JSON they came from:
Same as the file: True.
The Complete File

using System.Text.Json;
// Settings from a file. Each value is a different kind of JSON.
string json = """[{"Name":"volume","Value":7},{"Name":"theme","Value":"dark"},{"Name":"window","Value":{"Width":800,"Height":600}}]""";
// Read: each Value keeps its piece of JSON as it is.
List<Setting> settings = JsonSerializer.Deserialize<List<Setting>>(json)!;
foreach (Setting setting in settings)
{
Console.WriteLine($"{setting.Name}: {setting.Value.ValueKind}, {setting.Value.GetRawText()}");
}
// Write: the same pieces of JSON go back out unchanged.
string written = JsonSerializer.Serialize(settings);
Console.WriteLine(written);
Console.WriteLine($"Same as the file: {written == json}");
// A setting's name, and its value as a piece of JSON of any kind.
record Setting(string Name, JsonElement Value);
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Declaring Value as string to keep the JSON as text | Reading the settings threw JsonException: The JSON value could not be converted to Setting., followed by the path $[0].Value: the number 7 isn't a string | Declare it as JsonElement, which takes any kind of JSON |
Putting JSON text in a string property to write it | new Setting("window", """{"Width":800,"Height":600}""") was written as a string, with every quote escaped: "Value":"{\u0022Width\u0022:800,\u0022Height\u0022:600}" | Keep it in a JsonElement: the example wrote "Value":{"Width":800,"Height":600} |
Creating a Setting with no value, as in new Setting("volume", default) | Its ValueKind was Undefined, and JsonSerializer.Serialize threw InvalidOperationException: Operation is not valid due to the current state of the object. | Give it a value: with JsonElement.Parse("7"), it was written as {"Name":"volume","Value":7} |
Reading a Value the JSON didn't have | For {"Name":"volume"}, ValueKind was Undefined, and GetRawText() threw the same InvalidOperationException | Check ValueKind first. The enum's reference for Undefined: There is no value (as distinct from Null). A JSON null gave ValueKind Null and the text null |
FAQ
Can I use object instead of JsonElement?
It ends up holding the same thing: with object Value, both values came back as a JsonElement. The JsonUnknownTypeHandling reference, for its JsonElement setting: A type declared as Object is deserialized as a JsonElement. But the compiler only knows it's an object, so the code has to cast it, as in (JsonElement)settings[1].Value, before it can read ValueKind or GetRawText(). A JsonElement property needs no cast.
How do I turn the value into a type later?
Convert it once your code knows what it holds. For the window, Value.Deserialize<WindowSize>() with a record WindowSize(int Width, int Height) gave WindowSize { Width = 800, Height = 600 }, and for the volume, Value.GetInt32() gave 7. The method's reference: Converts the JsonElement representing a single JSON value into a TValue.
Are the spaces inside the JSON kept?
GetRawText() keeps them, because it returns the original text, but writing doesn't. For a window value of { "Width": 800, "Height": 600 }, GetRawText() returned it with its spaces, and JsonSerializer.Serialize wrote {"Name":"window","Value":{"Width":800,"Height":600}}. The values and their order stayed the same.
Conclusion
Declare a property as JsonElement, and a record or class keeps a piece of JSON of any kind: System.Text.Json reads it as it is and writes it back unchanged, apart from spaces. Check ValueKind before you read it, give it a value before you write it, and turn it into a type with Deserialize<T>() once your code knows what it holds.
Additional Resources
- JsonElement — the type, with its
ValueKindproperty andGetRawText()method. - Deserialize into JsonElement or JsonNode — a property that takes any JSON, with a round-trip example.
- JsonValueKind — the kinds of JSON value, and
Undefined. - JsonUnknownTypeHandling — what an
objectproperty is read as. - JsonSerializer.Deserialize — including the overloads that convert a
JsonElement.
