Question

Deserialize JSON into a C# dynamic Object

csharp.netjsonserializationdynamic

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.Json can deserialize into dynamic, JObject, or JToken
  • System.Text.Json usually works better with JsonDocument, JsonElement, or custom classes rather than true dynamic

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.

Take Quiz

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((int)obj["age"]);

Nested JSON example

using System;
using Newtonsoft.Json;

string json = @"{
  ""user"": {
    ""name"": ""Sam"",
    ""email"": ""sam@example.com""
  }
}";

dynamic data = JsonConvert.DeserializeObject<dynamic>(json);

Console.WriteLine(data.user.name);
Console.WriteLine(data.user.email);

This works well for quick scripts or exploratory code, but in larger applications, strongly typed models are usually easier to maintain.

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:

  1. A JSON string is created:

    {
      "product": "Laptop",
      "price": 1200
    }
    
  2. JsonConvert.DeserializeObject<dynamic>(json) reads the JSON text.

  3. The JSON library builds an object representation in memory.

  4. The variable item is declared as dynamic, so C# delays member checking until runtime.

  5. item.product is resolved at runtime and returns "Laptop".

  6. item.price is resolved at runtime and returns 1200.

If you try to access a missing property, such as:

Console.WriteLine(item.category);

you may get runtime behavior that is harder to debug than with strongly typed classes. That is one of the main costs of using dynamic.

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.

Take Quiz

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.

5. Prefer typed models for business logic

Once JSON data becomes important to application behavior, typed classes are usually better for maintainability, testing, and refactoring.

Common Mistakes

1. Assuming dynamic is supported the same way in every JSON library

Not all C# JSON libraries treat dynamic equally.

  • Newtonsoft.Json supports it well
  • System.Text.Json does 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 JObject with 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

4. Using dynamic for long-term application models

dynamic is tempting at first, but large codebases become harder to maintain when everything is loosely typed.

How to avoid it:

  • Use dynamic for quick parsing or uncertain input
  • Convert to typed classes for core application logic

5. Forgetting type conversions

JSON values may need conversion:

JObject obj = JObject.Parse(@"{ ""age"": ""30"" }");
int age = (int)obj["age"]; // may fail if stored as a string

Safer approach:

int age = int.Parse((string)obj["age"]);

Comparisons

ApproachBest forProsCons
Strongly typed classesStable JSON structureCompile-time safety, autocomplete, easy refactoringRequires creating classes
dynamic with Newtonsoft.JsonQuick access to unknown or changing JSONFast to write, flexibleRuntime errors, less safe
JObject / JTokenPartial or inspected JSON accessExplicit, flexible, good for validationMore verbose than dynamic
System.Text.Json with JsonDocument / JsonElementModern built-in JSON handlingFast, built into .NETLess convenient for dynamic-style access

dynamic vs strongly typed classes

// dynamic
var data = JsonConvert.DeserializeObject<dynamic>(json);
Console.WriteLine(data.name);
// strongly typed
public class User
{
    public string Name { get; set; }
}

User user = JsonConvert.DeserializeObject<User>(json);
Console.WriteLine(user.Name);

If the JSON structure is known and important, strongly typed classes are usually the better choice.

Take Quiz

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 dynamic when JSON shape is unknown or temporary
  • Use typed classes when the structure is stable
  • Prefer JObject if you want explicit key-based access
  • Be careful: property name errors with dynamic happen 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.

When should I create C# classes instead of using dynamic?

Create classes when the JSON structure is known, reused, or important to your application logic.

Take Quiz

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

  1. Create a JSON string containing a user's name, age, and city.
  2. Deserialize the JSON without defining a custom C# model class.
  3. Print each value to the console.
  4. Also show an alternative using JObject.
  5. Keep the program runnable as a simple console app.
Take Quiz

Keep learning

Related questions

View more