How can I deserialize JSON with dynamic key names in C#?
Jan 07, 2025 pm 12:41 PMDeserializing Child Objects with Dynamic Key Names
Introduction
Serializing JSON data with varying key names poses a challenge in deserialization. This article explores a solution using a dynamic property pattern in C#.
Problem Statement
Considering the JSON data below, how can we deserialize it while maintaining the dynamic "numeric" keys?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
Solution
Dynamic Property Pattern
We can represent the varying keys using a Dictionary<string, T> where T is a class containing the child object data. In this case, we declare the following classes:
1 2 3 4 5 6 7 8 9 10 11 |
|
Deserialization
To deserialize the JSON using the dynamic property pattern, we use the following code:
1 |
|
This creates an instance of RootObject, with a Dictionary<string, User> property named users populated with the deserialized child objects.
Accessing Object Data
Now, we can access each child object using their respective keys by iterating over the users dictionary:
1 2 3 4 5 |
|
Demo
The following C# code demonstrates the entire process:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
|
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
The above is the detailed content of How can I deserialize JSON with dynamic key names in C#?. For more information, please follow other related articles on the PHP Chinese website!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

What are the types of values returned by c language functions? What determines the return value?

C language function format letter case conversion steps

What are the definitions and calling rules of c language functions and what are the

Where is the return value of the c language function stored in memory?

How do I use algorithms from the STL (sort, find, transform, etc.) efficiently?

How does the C Standard Template Library (STL) work?
