Question
Is there a way to deserialize JSON content into a C# dynamic type?
I would like to avoid creating many C# classes just to use DataContractJsonSerializer for JSON parsing. Is it possible to deserialize JSON directly into a dynamic object and access its properties at runtime?
Short Answer
By the end of this page, you will understand how JSON deserialization works in C#, how dynamic can be used to work with JSON without defining many model classes, and when this approach is useful versus when strongly typed classes are a better choice.
Concept
JSON deserialization is the process of converting a JSON string into a C# object.
In C#, there are two common ways to work with JSON data:
- Strongly typed deserialization: map JSON into C# classes
- Dynamic or loosely typed deserialization: inspect and access values at runtime without fixed classes
Using dynamic can be helpful when:
- The JSON structure is unknown ahead of time
- The structure changes often
- You only need a few fields
- You want to quickly inspect API responses
However, dynamic comes with trade-offs:
- You lose compile-time checking
- Property name mistakes are only found at runtime
- Refactoring is harder
- IDE autocomplete is limited or unavailable
In modern C#, JSON libraries typically handle this in one of these ways:
Newtonsoft.Jsoncan deserialize intodynamic,JObject, orJTokenSystem.Text.Jsonusually works better withJsonDocument,JsonElement, or custom classes rather than truedynamic
This matters in real programming because developers often consume external APIs where the JSON may be large, partially relevant, or inconsistent. Knowing when to use dynamic helps you move quickly without sacrificing too much safety.
Mental Model
Think of strongly typed deserialization like filling out a printed form with fixed boxes:
- A box exists for
Name - A box exists for
Age - The data must fit those boxes
Think of dynamic deserialization like receiving a package of labeled items and opening it as needed:
- You do not prepare boxes in advance
- You look inside at runtime
- You read only the labels you care about
This is flexible, but also riskier. If you expect a label called name and the package contains fullName, your code may fail at runtime.
Syntax and Examples
In practice, the most common way to deserialize JSON into something dynamic in C# is with Newtonsoft.Json.
Example with dynamic
using System;
using Newtonsoft.Json;
string json = @"{
""name"": ""Alice"",
""age"": 30,
""active"": true
}";
dynamic data = JsonConvert.DeserializeObject<dynamic>(json);
Console.WriteLine(data.name);
Console.WriteLine(data.age);
Console.WriteLine(data.active);
What this does
DeserializeObject<dynamic>(json)parses the JSON string- The result can be accessed with property syntax like
data.name - Property resolution happens at runtime
Example with JObject
JObject is often safer and clearer than dynamic because it makes the JSON nature of the data explicit.
using System;
using Newtonsoft.Json.Linq;
string json = @"{
""name"": ""Alice"",
""age"": 30
}";
JObject obj = JObject.Parse(json);
Console.WriteLine((string)obj["name"]);
Console.WriteLine(()obj[]);
Step by Step Execution
Consider this example:
using System;
using Newtonsoft.Json;
string json = @"{
""product"": ""Laptop"",
""price"": 1200
}";
dynamic item = JsonConvert.DeserializeObject<dynamic>(json);
Console.WriteLine(item.product);
Console.WriteLine(item.price);
Here is what happens step by step:
-
A JSON string is created:
{ "product": "Laptop", "price": 1200 } -
JsonConvert.DeserializeObject<dynamic>(json)reads the JSON text. -
The JSON library builds an object representation in memory.
-
The variable
itemis declared asdynamic, so C# delays member checking until runtime. -
item.productis resolved at runtime and returns"Laptop". -
item.priceis resolved at runtime and returns .
Real World Use Cases
Using dynamic JSON handling in C# is useful in several practical situations:
Quick API exploration
When testing a third-party API, you may only need a few fields from a large response.
string json = GetApiResponse();
dynamic result = JsonConvert.DeserializeObject<dynamic>(json);
Console.WriteLine(result.status);
Logging and diagnostics
If you want to inspect arbitrary JSON payloads without creating dedicated model types, dynamic parsing can save time.
Admin tools and internal utilities
Internal scripts often process changing JSON formats where strict model classes would be too much overhead.
Partial data extraction
If a JSON document contains 50 fields and you only care about 2, using dynamic or JObject may be simpler than building full classes.
Prototyping
During early development, teams sometimes start with dynamic parsing and later replace it with strongly typed models once the API format becomes stable.
Real Codebase Usage
In real codebases, developers usually avoid using raw dynamic everywhere. Instead, they use it selectively.
Common patterns
1. Parse loosely at the edges
When receiving data from external systems, developers may first inspect JSON using JObject or JsonDocument, then map only the needed values into typed objects.
2. Validate before use
Before reading properties, production code often checks whether they exist.
using Newtonsoft.Json.Linq;
JObject obj = JObject.Parse(json);
if (obj["name"] != null)
{
Console.WriteLine((string)obj["name"]);
}
3. Use guard clauses
Developers often fail early if required fields are missing.
if (obj["id"] == null)
{
throw new Exception("Missing required field: id");
}
4. Convert to typed models later
A common pattern is:
- Read incoming JSON loosely
- Validate required fields
- Map into a proper domain model
This gives flexibility at the boundary and safety inside the application.
Common Mistakes
1. Assuming dynamic is supported the same way in every JSON library
Not all C# JSON libraries treat dynamic equally.
Newtonsoft.Jsonsupports it wellSystem.Text.Jsondoes not behave the same way for true dynamic member access
2. Misspelling property names
This compiles, but may fail at runtime:
using Newtonsoft.Json;
string json = @"{ ""name"": ""Alice"" }";
dynamic data = JsonConvert.DeserializeObject<dynamic>(json);
Console.WriteLine(data.nmae); // typo
How to avoid it:
- Use strongly typed classes when structure is known
- Use
JObjectwith explicit key access when needed
3. Ignoring missing fields
Broken assumption:
Console.WriteLine(data.address.city);
If address does not exist, this can cause runtime errors.
How to avoid it:
- Check for existence first
- Use safer parsing logic
Comparisons
| Approach | Best for | Pros | Cons |
|---|---|---|---|
| Strongly typed classes | Stable JSON structure | Compile-time safety, autocomplete, easy refactoring | Requires creating classes |
dynamic with Newtonsoft.Json | Quick access to unknown or changing JSON | Fast to write, flexible | Runtime errors, less safe |
JObject / JToken | Partial or inspected JSON access | Explicit, flexible, good for validation | More verbose than dynamic |
System.Text.Json with JsonDocument / JsonElement | Modern built-in JSON handling | Fast, built into .NET |
Cheat Sheet
// Newtonsoft.Json dynamic
using Newtonsoft.Json;
dynamic data = JsonConvert.DeserializeObject<dynamic>(json);
Console.WriteLine(data.name);
// Newtonsoft.Json JObject
using Newtonsoft.Json.Linq;
JObject obj = JObject.Parse(json);
string name = (string)obj["name"];
int age = (int)obj["age"];
Quick rules
- Use
dynamicwhen JSON shape is unknown or temporary - Use typed classes when the structure is stable
- Prefer
JObjectif you want explicit key-based access - Be careful: property name errors with
dynamichappen at runtime - Validate required fields before using them
Good default choice
- For quick, flexible JSON parsing:
Newtonsoft.Json - For long-term maintainable code: strongly typed models
Watch out for
- Misspelled property names
- Missing nested objects
- Unexpected JSON value types
- Different behavior between JSON libraries
FAQ
Can I deserialize JSON directly into dynamic in C#?
Yes. With Newtonsoft.Json, you can use JsonConvert.DeserializeObject<dynamic>(json).
Does DataContractJsonSerializer work well with dynamic?
Not really. It is designed more for strongly typed serialization and deserialization.
Is dynamic a good replacement for model classes?
Usually no. It is useful for quick parsing, unknown structures, or prototypes, but typed classes are better for maintainable applications.
What is better than dynamic for loosely structured JSON?
JObject or JToken are often better because they make property access more explicit and easier to validate.
Should I use System.Text.Json or Newtonsoft.Json for dynamic JSON?
If you specifically want dynamic-style access, Newtonsoft.Json is generally more convenient.
What happens if a property does not exist on a dynamic JSON object?
You may get a runtime error or unexpected behavior, depending on how the JSON object is represented.
Mini Project
Description
Build a small C# console program that reads a JSON string representing a user profile and prints selected values without creating a dedicated C# class. This demonstrates when dynamic JSON parsing is convenient for quick tools and prototypes.
Goal
Parse JSON into a flexible object and safely read a few values from it.
Requirements
- Create a JSON string containing a user's name, age, and city.
- Deserialize the JSON without defining a custom C# model class.
- Print each value to the console.
- Also show an alternative using
JObject. - Keep the program runnable as a simple console app.
Keep learning
Related questions
AddTransient vs AddScoped vs AddSingleton in ASP.NET Core Dependency Injection
Learn the differences between AddTransient, AddScoped, and AddSingleton in ASP.NET Core DI with examples and practical usage.
Best Way to Repeat a Character in C#: Building Repeated Strings Efficiently
Learn the best way to repeat a character in C#, compare StringBuilder, string concatenation, and simpler built-in options.
C# Array Initialization Syntaxes Explained
Learn all common C# array initialization syntaxes with examples, rules, comparisons, and mistakes beginners often make.