Как десериализовать json c


C# JSON tutorial shows how to work JSON data in C# using the classes of the standard library.

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easily read and written by humans and parsed and generated by machines. The application/json is the official Internet media type for JSON. The JSON filename extension is .json .

In this article, we work with the C# standard library. There is also a popular third-party library called Json.NET .


The System.Text.Json namespace provides high-performance, low-allocating, and standards-compliant tools to work with JSON. The classes allow us to serialize objects into JSON text and deserialize JSON text to objects. The UTF-8 support is built-in.

C# JSON parse

The JsonDocument.Parse parses a stream as UTF-8-encoded data representing a single JSON value into a JsonDocument . The stream is read to completion.

In the example, we parse a simple JSON string.

We parse the JSON string into a JsonDocument .

We get the reference to the root element with the RootElement property.

With the [] operator, we get the first and the second subelements of the JSON document.

We get the properties of an element with GetProperty .

C# JSON enumerate

The JsonElement.EnumerateArray enumerates the values in the JSON array represented by a JsonElement .

In the example, we enumerate the contents of the root element.

We get the array of subelements.

In a while loop, we go over the array of elements.

In the second while loop, we go over the properties of each element.

C# JSON serialize

The JsonSerializer.Serialize converts the value of a specified type into a JSON string.

In the example, we convert a User object into a JSON string.

C# JSON deserialize

The JsonSerializer.Deserialize parses the text representing a single JSON value into an instance of a specified type.

The example parses the JSON string into an instance of the User type.

C# JsonSerializerOptions

With JsonSerializerOptions , we can control the process of serialization with some options.

With the WriteIndented option set, we enable indentation for pretty printing.

C# Utf8JsonWriter

The Utf8JsonWriter provides a high-performance API for forward-only, non-cached writing of UTF-8 encoded JSON text.

In the example, we create a new object and write it into a JSON string.

We can set the Indented option to true to beautify the JSON output.

In the example, we write a JSON string into a file. The data is prettyfied.

C# JSON Utf8JsonReader

The Utf8JsonReader orovides a high-performance API for forward-only, read-only access to UTF-8 encoded JSON text.

In the example, we read JSON data from a file with Utf8JsonReader . It provides a low-level API for reading JSON data. We read the data token by token.

C# JSON parse async

In the following example, we read a stream asynchronously with JsonDocument.ParseAsync .

The example reads all releases of the .NET Core framework, which are available as a JSON string on the project Github repository.

C# HttpClient GetFromJsonAsync

The GetFromJsonAsync method sends a GET request to the specified URL and returns the value that results from deserializing the response body as JSON in an asynchronous operation.

The method is an extension method from System.Net.Http.Json .

We create an asynchronous http request to a JSON resource. The JSON data is serialized into a list of User objects.

The GetFromJsonAsync is a convenience method which transforms JSON resource into C# collections.

Deserialize JSON with C#

I’m trying to deserialize a Facebook friend’s Graph API call into a list of objects. The JSON object looks like:

It’s not working, because the primitive object is invalid. How can I deserialize this?

Peter Mortensen's user avatar

10 Answers 10

You need to create a structure like this:

Then you should be able to do:

The names of my classes are just an example. You should use proper names.

Adding a sample test:

Peter Mortensen's user avatar

Icarus's user avatar

Sometimes I prefer dynamic objects:

Aman Agnihotri's user avatar

Bishoy Hanna's user avatar

A great way to automatically generate these classes for you is to copy your JSON output and throw it in here:

It will provide you with a starting point to touch up your classes for deserialization.

Very easily we can parse JSON content with the help of dictionary and JavaScriptSerializer. Here is the sample code by which I parse JSON content from an ashx file.

Peter Mortensen's user avatar

Newtonsoft.JSON is a good solution for these kind of situations. Also Newtonsof.JSON is faster than others, such as JavaScriptSerializer , DataContractJsonSerializer .

In this sample, you can the following:

Then you can cast jsonData to JArray , and you can use a for loop to get data at each iteration.

Also, I want to add something:

Working with dynamic object and using Newtonsoft serialize is a good choice.

Peter Mortensen's user avatar

I agree with Icarus (would have commented if I could), but instead of using a CustomObject class, I would use a Dictionary (in case Facebook adds something).

Peter Mortensen's user avatar

Stijn Bollen's user avatar



To deserialize a dynamic object

Peter Mortensen's user avatar

If you’re using .NET Core 3.0, you can use System.Text.Json (which is now built-in) to deserialize JSON.

The first step is to create classes to model the JSON. There are many tools which can help with this, and some of the answers here list them.

Some options are http://json2csharp.com, http://app.quicktype.io, or use Visual Studio (menu EditPaste SpecialPaste JSON as classes).

Then you can deserialize using:

If you need to add settings, such as camelCase handling, then pass serializer settings into the deserializer like this:

Работа с JSON

JSON (JavaScript Object Notation) является одним из наиболее популярных форматов для хранения и передачи данных. И платформа .NET предоставляет функционал для работы с JSON.

Основная функциональность по работе с JSON сосредоточена в пространстве имен System.Text.Json . Ключевым типом является класс JsonSerializer , который и позволяет сериализовать объект в json и, наоборот, десериализовать код json в объект C#.

Для сохранения объекта в json в классе JsonSerializer определен статический метод Serialize() и его асинхронный двойник SerializeAsyc() , которые имеют ряд перегруженных версий. Некоторые из них:

string Serialize(Object obj, Type type, JsonSerializerOptions options) : сериализует объект obj типа type и возвращает код json в виде строки. Последний необязательный параметр options позволяет задать дополнительные опции сериализации

string Serialize<T>(T obj, JsonSerializerOptions options) : типизированная версия сериализует объект obj типа T и возвращает код json в виде строки.

Task SerializeAsync(Stream utf8Json, Object obj, Type type, JsonSerializerOptions options) : сериализует объект obj типа type и записывает его в поток utf8Json. Последний необязательный параметр options позволяет задать дополнительные опции сериализации

Task SerializeAsync<T>(Stream utf8Json, T obj, JsonSerializerOptions options) : типизированная версия сериализует объект obj типа T в поток utf8Json.

Для десериализации кода json в объект C# применяется метод Deserialize() и его асинхронный двойник DeserializeAsync() , которые имеют различные версии. Некоторые из них:

object? Deserialize(string json, Type type, JsonSerializerOptions options) : десериализует строку json в объект типа type и возвращает десериализованный объект. Последний необязательный параметр options позволяет задать дополнительные опции десериализации

T? Deserialize<T>(string json, JsonSerializerOptions options) : десериализует строку json в объект типа T и возвращает его.

ValueTask<object?> DeserializeAsync(Stream utf8Json, Type type, JsonSerializerOptions options, CancellationToken token) : десериализует данные из потока utf8Json, который представляет объект JSON, в объект типа type. Последние два параметра необязательны: options позволяет задать дополнительные опции десериализации, а token устанавливает CancellationToken для отмены задачи. Возвращается десериализованный объект, обернутый в ValueTask

ValueTask<T?> DeserializeAsync<T>(Stream utf8Json, JsonSerializerOptions options, CancellationToken token) : десериализует данные из потока utf8Json, который представляет объект JSON, в объект типа T. Возвращается десериализованный объект, обернутый в ValueTask

Рассмотрим применение класса на простом примере. Сериализуем и десериализуем простейший объект:

Здесь вначале сериализуем с помощью метода JsonSerializer.Serialize() объект типа Person в стоку с кодом json. Затем обратно получаем из этой строки объект Person посредством метода JsonSerializer.Deserialize() .

Хотя в примере выше сериализовался/десериализовался объект класса, но подобным способом мы также можем сериализовать/десериализовать структуры.

Некоторые замечания по сериализации/десериализации

Объект, который подвергается десериализации, должен иметь либо конструктор без параметров, либо конструктор, для всех параметров которого в десериализуемом json-объекте есть значения (соответствие между параметрами конструктора и свойствами json-объекта устанавливается на основе названий, причем регистр не играет значения).

Сериализации подлежат только публичные свойства объекта (с модификатором public).

Запись и чтение файла json

Поскольку методы SerializeAsyc/DeserializeAsync могут принимать поток типа Stream, то соответственно мы можем использовать файловый поток для сохранения и последующего извлечения данных:

В данном случае вначале данные сохраняются в файл user.json и затем считываются из него.

Настройка сериализации с помощью JsonSerializerOptions

По умолчанию JsonSerializer сериализует объекты в минимифицированный код. С помощью дополнительного параметра типа JsonSerializerOptions можно настроить механизм сериализации/десериализации, используя свойства JsonSerializerOptions. Некоторые из его свойств:

AllowTrailingCommas : устанавливает, надо ли добавлять после последнего элемента в json запятую. Если равно true , запятая добавляется

DefaultIgnoreCondition : устанавливает, будут ли сериализоваться/десериализоваться в json свойства со значениями по умолчанию

IgnoreReadOnlyProperties : аналогично устанавливает, будут ли сериализоваться свойства, предназначенные только для чтения

WriteIndented : устанавливает, будут ли добавляться в json пробелы (условно говоря, для красоты). Если равно true устанавливаются дополнительные пробелы

Настройка сериализации с помощью атрибутов

По умолчанию сериализации подлежат все публичные свойства. Кроме того, в выходном объекте json все названия свойств соответствуют названиям свойств объекта C#. Однако с помощью атрибутов JsonIgnore и JsonPropertyName .

Атрибут JsonIgnore позволяет исключить из сериализации определенное свойство. А JsonPropertyName позволяет замещать оригинальное название свойства. Пример использования:

В данном случае свойство Age будет игнорироваться, а для свойства Name будет использоваться псевдоним «firstname». Консольный вывод:

Обратите внимание, что, поскольку свойство Age не было сериализовано, то при десериализации для него используется значение по умолчанию.

Deserializing JSON with c#

This tutorial details how to deserialize* a JSON “string” into a c# object using JSON.net by Newtonsoft. It’s a stand alone tutorial, but follows logically from Consuming a REST API from c#.

* It pains me to use a ‘z’ here but I need to keep the US audiences and search engines happy!

If you prefer video to the written word, you can find the accompanying YouTube video here:

User Story

As a developer
I want to parse, (deserialize), a JSON string
So that I can work with c# objects

Acceptance Criteria

By the end of this tutorial you should be able to:

  • Understand what JSON is and how it’s structured
  • Deserialize JSON Strings


  • Windows PC (to run Visual Studio)
  • Visual Studio (I use the Community Edition)
  • JSON Editor Online @ http://jsoneditoronline.org/ (you can use an alternative I just like this one)
  • 20 Minutes of your time

User Interface Design

Using Balsamiq the following wire frame emerged and helped clarify my thinking, it’s pretty simple really… It takes and input, input is processed by clicking the button and the output is shown in the bottom plane. There’s a 2nd button that clears the output window.

A good wire frame should speak for its self though, so here you go:

Wire Frame – Realized

So here’s what the wire frame translates to in the real world, I’ve place the form element names there if you’re wanting to use the same naming convention as me, (not sure why you would my naming convention is pretty rubbish!):

Point to note, both textboxes are set to “Multiline: True” and with vertical scroll bars…

“Wire Up” The Buttons

Ok, so let’s do some simple stuff first, double click each button on the form designer to invoke their click event handlers.

Into the “cmdClear” button’s handler place the very simple code:

If you don’t understand what that’s doing then you may struggle with the rest of the tutorial, so moving on!

I also, (as in previous tutorials), like to add my little “debugOutput” function that takes a string, displays it on a multi-line text box and “scrolls” to the next line, so further text can be displayed. So inside your Form code, add the following function, (it’s not mandatory for the actual parsing of JSON, but it just looks nice):

Let’s test the function by adding the following code to the cmdDeserialise Click event handler. Test it by typing something in txtInput, and clicking cmdDeserialise…

Yeah – amazing right?

So what is JSON?

I’m going to guess if you’re reading this you have some idea… So I don’t really want to go over in vast detail what it is here as there are plenty of great written resources already, (check out the Wikipedia entry here).

What I do want to do though is labor some points that will come in useful when we start deserializing the raw JSON strings…

  • Stands for: “JavaScript Object Notation”
  • Open format used for the transmission of “object” data, (primarily), over the web.
  • It consists of attribute-value pairs, (see examples below)
  • A JSON Object can contain other “nested” objects
Anatomy of a Simple JSON Object

In the above example we have a “Person” object with 4 attributes:

  • firstname
  • lastname
  • age
  • isAlive

With the following respective values:

  • Roger [This is a string data-type and is therefore delineated by double quotes ‘ ” ‘ ]
  • Moore [Again this is a string and needs double quotes
  • 89 [Number value that does not need quotes]
  • false [Boolean value, again does not need the double quotes]

Paste this JSON into something like jsoneditoronline.org, and you can interrogate its structure some more, (possibly not that useful for such a simple object…)

A, (slightly), more complex example

As mentioned in the overview of JSON, an object can contain “nested” objects, observe our person example above with a nested address object:

Here we can see that we have a 5th Person object attribute, address, which does not have a standard value like the others, but in fact contains another object with 3 attributes:

  • streetAddress
  • city
  • postcode

The values of all these attributes contains strings, so no need to labor that point further!

This nesting can continue ad-nauseum

Again posting this JSON into our online editor yields a slightly more interesting structure:

A final example

Onto our last example which this time includes an array of phone number objects:

Note: I removed: “age” and “isAlive” attributes from the person object as well as the “postcode” attribute from the address object purely for brevity.

You’ll observe that we added an additional attribute to our Person object, “phonenNumbers”, and unlike the “address” attribute it’s contains an array of other objects as opposed to just a single nested object.

So What?

So why did I detail these JSON examples, we’ll firstly it was to get you familiar with JSON and some of its core constructs, specifically:

  • The start and end of an object: ‘ ‘
  • Attribute-Value pairs
  • Nested Objects, (or objects as attribute values)
  • Array of Objects

Personally on my JSON travels these constructs are the main one’s you’ll come across, and as far as an introduction goes, should give you pretty good coverage of most scenarios.

Secondly, we’ll be using these examples in deserializing JSON with JSON.Net, so lets’s get started on that!

Installing JSON.NET

The best way to install JSON.Net into your Visual Studio project, (i think), is to use the NuGet Package Manager Console. So in your project, do the following:

Once in the Package Manager Console, type:

You should also be able to see JSON.Net in the list of Project References:

OK, We’re Ready to Code

In order to deserialize a JSON string we’re going to use the JsonConvert class from the JSON.Net framework, then use the DesrializeObject method, a link to the Newtonsoft web site can be found HERE, detailing this approach.

Let’s be Dynamic

Ok our first example requires the least coding, first create a new method in your form’s code called: deserialiseJSON, as follows:

Now update the click event of our deserialize button:

This just means we’re almost ready to start deserializing!

Go Back to our deserialiseJSON method, and in our try block, add the following code:

So what have we done here?

  • Created a variable (var) called jPerson. This will hold our deserialised JSON object
  • Used the DeserializeObject method of the JsonConvert class
  • Used the “dynamic” object as a place holder for our “type” – more on this below
  • Passed in what ever serialized, “raw”, json string is in our first text box

It’s the use of dynamic that’s most interesting here. This basically tells Visual Studio that we’ll have to wait until run time before our object dependencies are resolved. In practice this means we can pass in any valid json string and the JSON/Net frameowrk will interpret and create a deserilaised c# object for us on the fly, (jPerson).

We can then access the attributes of jPerson, and treat it like a regular object.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *