C# — WEB HTTP SERVICE AND JSON IN C#


Содержание

JSON в HTTP ответе

15.08.2020, 21:57

Как получить (HTML) тело aspx страницы при ответе сервера “HTTP/1.1 500 Internal Server Error»?
Нужно получить исходный код с ошибкой (именно при ответе сервера 500 Internal Server Error) aspx.

Как получить из строки JSON токен используя JSON.NET?
Доброго времени суток, Господа. Поскажите пожалуйста. Я никогда не работал с JSON. Вот тут решил.

16.08.2020, 00:15 2

дальше JSON конвертер.

16.08.2020, 21:25 [ТС] 3 17.08.2020, 00:24 4

Saron, вы на одном клиенте запускаете параллельно несколько запросов, так нельзя. Один клиент — один запрос. Хотите делать много запросов одновременно — для каждого создавайте отдельный webclient. Либо используйте HttpClient, он в многопоток умеет с одного инстанса.

Добавлено через 1 минуту
Saron, и там есть 2 версии методов: синхронные и асинхронные (Если речь идет о WebClient).

WCF REST Service with JSON Data

Many times there is need to get the output in different message format such as XML,JSON or custom message format to fulfill the software requirement. So in this article we will learn how create WCF REST Service which return JSON format output .

Prerequisites
To understand WCF REST service, you need to at-least beginner knowledge on WCF ,if you are beginner in WCF then please refer my following articles of WCF.

  1. Introduction to WCF Services
  2. Introduction To WCF Endpoints
  3. Creating WCF Service

I hope you have read above articles , now let us start with WCF REST from definition

What is WCF REST ?
REST stands for Representational state transfer which is technique to communicate on cross platform application and exchange the data in JSON or XML format with the help of GET,POST,PUT,DELETE methods of HTTP protocol.

To return JOSN as output we need to set RequestFormat of WebMessageFormat to JSON in REST template which we will learn in next.

let us briefly understand about the HTTP methods which is most commonly used to create WCF REST service as:

  • GET : Get the resource (Records) from particular source such as SQL database.
  • POST : Used to insert the records into the particular source such as SQL, Oracle database.
  • PUT : Used to modify the resource or records.
  • DELETE : used Delete the specific resource or record from particular source.

I hope you understand basic about REST concept , Now let us start step by step to create WCF REST JSON Service.

Step 1: Create WCF Service.

To know how to create WCF service in depth please refer my article Creating WCF Service . So In this let see simple way to create WCF service:

  1. «Start» — «All Programs» — «Microsoft Visual Studio 2015».
  2. «File» — «New Project» — «C#» — WCF Service Application as shown in below.

3 .Provide the project name such as «PayMentRESTService » or another as you wish and specify the location.

4. Now delete the auto created Interface and svc file which we will create new one so beginners can understand it.

5. Now Add New WCF Service file and give name PayMentRESTService are as:
I hope you have followed the same steps and and learned how to add WCF Service. After adding Service file then the project solution explorer will be look like as follows

Step 2: Configure REST Service Template.

Now open the the IPaymentService.cs Interface file and write the following code:

Let us understand above REST Template using following diagram

I hope you have understood the basic REST Template from above image.In the above example we set WebMessageFormat is JSON , So it will return the JSON format output.

Step 3: Implement IPaymentService.cs interface methods into PaymentService.svc.cs file as.

Now our REST Service Code is ready ,lest us complete another more steps.
Download Aspose : API To Create and Convert Files

Step 4: Configure End Points and Service Behaviors in web.config file as:

End Points and Service Behaviors configuration is very important in WCF Service ,many people saying it much complicated to configure but trust me its much easier and simple with powerful intellisense. Lets open web.config file and find system.serviceModel tag and follow below steps

Configure service behaviors as:

Configure End points as:

While configuring Endpoints Tag automatically shows how to set and what contract because it shows list of contract files (Interfaces) i.e. service contract .I hope you got basic idea about the End points configuration . Soon I will post video on this. After configuring Endpoints and service behaviors the system.serviceModel tag section of web.config file will be look like as follows:

I hope you have done same configuration which i have done .


Step 5: Test REST Service.

Now our service is ready .lets test it using REST client of Mozilla browser are as

Our REST Service URL will be http://localhost:64858/PayMentService.svc/PayBill/100

From preceding output its clear that out service executed successfully and as per configuration its returned JSON output .Hope from preceding examples we have learned how to create WCF REST Service.
Note:

  • Configure the database connection in the web.config file depending on your database server location.
  • Download the Zip file of the sample application for a better understanding.
  • Since this is a demo, it might not be using proper standards, so improve it depending on your skills.

Summary

I hope this article is useful for all readers. If you have any suggestion then please contact me.
Download Aspose : API To Create and Convert Files

Jeremy Davis

Sitecore, C# and web development

JSON web services when you’re stuck in with basic ASP.Net…

Whilst it’s nice and easy to create JSON services for your front-end JavaScript if you’re working in ASP.Net MVC, things can be a bit more difficult to wire together if you find yourself with project requirements that force you to work with the older bits of ASP.Net. Getting the JSON inputs and outputs to work can caused me some head-scratching.

Having had to make this work recently, I thought I’d write down where I ended up after searching Stack Overflow and MSDN…

Setting up a simple service

When you try to add an item to a simple ASP.Net web project to implement a JSON service, there’s quite a lot of choice:

The simplest type to choose for is the classic “Web Service” – which generates you an ASMX file. While these default to being SOAP web services, we can give them some simple configuration to make them work with JSON. (As long as you’re using .Net 3.5 or newer) And they also don’t need any fancy configuration in the web.config – which is a bonus come deployment time.

When you create a new service you get a code-behind file that looks like this:

To get JSON into and out of your service, you need to make a few changes to attributes on the class and on any methods you create. The ScriptService attribute mentioned in the comments can replace the two WebService related ones. And the ScriptMethod attribute needs adding to each method you create along with the WebMethod :

The ResponseFormat property for the ScriptMethod attribute is what we need to get JSON as a return value.

Exchanging JSON

So now you’ve got a method, what do you need to do to exchange some JSON with your front-end scripts?

Well on the server side, it’s fairly easy – much as you would do in an MVC project. You can just define some classes to represent your input and output data structures, and the magic in the WebService class will deal with trying to convert your data to and from JSON.

For example, you can create a quick test method like so:

The input data type contains a string and an integer, and the method processes the string and turns the integer into a list of integers. Nothing exciting or clever – but enough to demonstrate what’s possible.

Then we need some script to call the service. This is based on jQuery’s Ajax framework:

The input data is a simple Javascript object here, with properties using the same names and types as the C#.

Then we need to set up the Ajax call. The first four properties we need to set are to do with sending data to the server:

  • The URL to call is the URL of your ASMX file, with the method name appended to the end.
  • The operation type being used to send the data here is a HTTP Post.
  • The content type for the data we’re posting is JSON.
  • And finally the data itself needs to be passed as JSON.

For the data property here, we need to do two things. Firstly, the object we send to the server needs to have the right property name to match the parameters of the server method. Hence the data we’re sending is – wrapping the parameters we’re sending correctly so that the web service can work out how to map the data to the method we’re calling.

And then we need to make sure that the data we send is JSON. The easiest way to achieve this is with the JSON.stringify() method. Modern browsers support this natively, and it turns any plain Javascript object passed in to a JSON string.

However it’s worth noting that if you’re using an older version of Sitecore and you need to support Internet Explorer for editors then this method can cause a problem. If your editors need to have Compatibility Mode enabled for the website you’re builfing then JSON.stringify() does not work. IE still claims to support it, but it doesn’t function.

If you need to work around this, then you should add a script reference to JSON2.js. This gives IE the ability back again, and works with or without Compatibility Mode.

And then the remaining two properties of the Ajax request are for receiving data:

  • The dataType property says you expect to get JSON back from the server.
  • And the success property lets you handle a successful result.
Цукерберг рекомендует:  Ждём всех на GeekWeek 2020

Obviously, you probably need to handle unsuccessful results as well…


The data object that your server code returned comes back to the success callback in the d property of whatever you call the parameter to your callback. But after that it’s just a plain object with the same properties as your server object. For example, the result coming back from this call looks like:

So with that code you can cover a lot of client-to-server calls.

It’s worth noting that while the JSON serialised that ASP.Net is using is pretty good, you still have to be careful about how you represent objects to send them from the client to the server. You can get 500 errors from your service when it fails to massage your JSON into .Net data structures.

I found the easiest way to work out what JSON the ASP.Net code is expecting to receive is to write the C# data structure you want to populate, fill in its properties, and then send it from the server to the client in a test message. That allows you to use your browser’s debugger to look at the object which arrives on the client. And that’s the structure you need to repeat in your client-side code.

Now to do something more interesting with this…

Вызов веб-API из клиента .NET (C#) Call a Web API From a .NET Client (C#)

Этом руководстве показано, как вызывать веб-API из приложения .NET с помощью System.Net.Http.HttpClient. This tutorial shows how to call a web API from a .NET application, using System.Net.Http.HttpClient.

В этом руководстве клиентского приложения записываются, которые используют следующие веб-API: In this tutorial, a client app is written that consumes the following web API:

Действие Action Метод HTTP HTTP method Относительный URI Relative URI
Получить продукт по Идентификатору Get a product by ID GET GET /API/продукты/идентификатор /api/products/id
Создать продукт Create a new product ПОМЕСТИТЬ POST / api/продуктов /api/products
Обновления продукта Update a product PUT PUT /API/продукты/идентификатор /api/products/id
Удалить продукт Delete a product DELETE DELETE /API/продукты/идентификатор /api/products/id

Чтобы узнать, как реализовать этот интерфейс API с веб-API ASP.NET, см. в разделе Создание веб-API, поддерживает операции CRUD. To learn how to implement this API with ASP.NET Web API, see Creating a Web API that Supports CRUD Operations.

Для простоты клиентское приложение в этом руководстве используется консольное приложение Windows. For simplicity, the client application in this tutorial is a Windows console application. HttpClient также поддерживается для приложений Windows Phone и Windows Store. HttpClient is also supported for Windows Phone and Windows Store apps. Дополнительные сведения см. в разделе код записи веб-API клиента для нескольких платформ с помощью переносимых библиотек For more information, see Writing Web API Client Code for Multiple Platforms Using Portable Libraries

Создание консольного приложения Create the Console Application

В Visual Studio создайте новое консольное приложение Windows с именем HttpClientSample и вставьте в него следующий код: In Visual Studio, create a new Windows console app named HttpClientSample and paste in the following code:

Приведенный выше код является полный клиентским приложением. The preceding code is the complete client app.

RunAsync запуски и блокируется до его завершения. RunAsync runs and blocks until it completes. Большинство HttpClient методы являются async, поскольку они выполняют подсистемы ввода/вывода. Most HttpClient methods are async, because they perform network I/O. Все асинхронные задачи выполняемые в RunAsync . All of the async tasks are done inside RunAsync . Обычно приложения не блокирует основной поток, но это приложение не допускает каких-либо взаимодействий. Normally an app doesn’t block the main thread, but this app doesn’t allow any interaction.

Установка библиотеки Web API клиента Install the Web API Client Libraries

С помощью диспетчера пакетов NuGet для установки пакета Web API клиентских библиотек. Use NuGet Package Manager to install the Web API Client Libraries package.

В меню Сервис последовательно выберите пункты Диспетчер пакетов NuGet > Консоль диспетчера пакетов. From the Tools menu, select NuGet Package Manager > Package Manager Console. В консоли диспетчера пакетов (PMC), введите следующую команду: In the Package Manager Console (PMC), type the following command:

Предыдущая команда добавляет в проект следующие пакеты NuGet: The preceding command adds the following NuGet packages to the project:

  • Microsoft.AspNet.WebApi.Client Microsoft.AspNet.WebApi.Client
  • Newtonsoft.Json Newtonsoft.Json

Json.NET — это популярная платформа JSON высокой производительности для .NET. Json.NET is a popular high-performance JSON framework for .NET.

Добавление класса модели Add a Model Class

Проверьте класс Product : Examine the Product class:

Этот класс соответствует модели данных, используемых веб-API. This class matches the data model used by the web API. Приложение может использовать HttpClient для чтения Product экземпляр HTTP-ответа. An app can use HttpClient to read a Product instance from an HTTP response. Приложение не нужно писать код десериализации. The app doesn’t have to write any deserialization code.

Создание и инициализация HttpClient Create and Initialize HttpClient

Изучите статический HttpClient свойство: Examine the static HttpClient property:

HttpClient будет должен создаваться один раз и повторно использоваться на протяжении всего жизненного цикла приложения. HttpClient is intended to be instantiated once and reused throughout the life of an application. Можно привести следующие условия SocketException ошибок: The following conditions can result in SocketException errors:

  • Создание нового HttpClient экземпляра на запрос. Creating a new HttpClient instance per request.
  • Сервер в условиях большой нагрузки. Server under heavy load.

Создание нового HttpClient экземпляра на запрос может исчерпать все доступные сокеты. Creating a new HttpClient instance per request can exhaust the available sockets.

В следующем примере кода инициализирует HttpClient экземпляр: The following code initializes the HttpClient instance:

Предыдущий код: The preceding code:

  • Задает базовый URI для HTTP-запросов. Sets the base URI for HTTP requests. Измените номер порта к порту, используемому в серверное приложение. Change the port number to the port used in the server app. Если не используется порт для серверного приложения для работы приложения. The app won’t work unless port for the server app is used.
  • Задает заголовок Accept «application/json». Sets the Accept header to «application/json». Параметр этот заголовок указывает, что сервер для отправки данных в формате JSON. Setting this header tells the server to send data in JSON format.


Отправка запроса GET для извлечения ресурса Send a GET request to retrieve a resource

Следующий код отправляет запрос GET для продукта: The following code sends a GET request for a product:

GetAsync метод отправляет запрос HTTP GET. The GetAsync method sends the HTTP GET request. Если метод завершается, она возвращает HttpResponseMessage , содержащий HTTP-ответа. When the method completes, it returns an HttpResponseMessage that contains the HTTP response. Если код состояния в ответе код успешного выполнения, текст ответа содержит представление JSON продукта. If the status code in the response is a success code, the response body contains the JSON representation of a product. Вызовите ReadAsAsync для полезных данных JSON для десериализации Product экземпляра. Call ReadAsAsync to deserialize the JSON payload to a Product instance. ReadAsAsync метод является асинхронным, поскольку текст ответа может быть произвольно большим. The ReadAsAsync method is asynchronous because the response body can be arbitrarily large.

HttpClient не выдает исключение при HTTP-ответа содержит код ошибки. HttpClient does not throw an exception when the HTTP response contains an error code. Вместо этого IsSuccessStatusCode свойство false Если состояние — код ошибки. Instead, the IsSuccessStatusCode property is false if the status is an error code. Если вы предпочитаете обрабатывать коды ошибок HTTP как исключения, вызвать HttpResponseMessage.EnsureSuccessStatusCode объекта response. If you prefer to treat HTTP error codes as exceptions, call HttpResponseMessage.EnsureSuccessStatusCode on the response object. EnsureSuccessStatusCode создает исключение, если код состояния находится вне диапазона 200–299. EnsureSuccessStatusCode throws an exception if the status code falls outside the range 200–299. Обратите внимание, что HttpClient может создавать исключения по другим причинам — к примеру, если тайм-аута запроса. Note that HttpClient can throw exceptions for other reasons — for example, if the request times out.

Модули форматирования типа мультимедиа для десериализации Media-Type Formatters to Deserialize

Когда ReadAsAsync вызывается без параметров, он использует набор по умолчанию модули форматирования мультимедиа прочитать текст ответа. When ReadAsAsync is called with no parameters, it uses a default set of media formatters to read the response body. Модули форматирования по умолчанию поддерживает JSON, XML и данные в форме кодировке к URL-адрес. The default formatters support JSON, XML, and Form-url-encoded data.

Вместо того чтобы использовать модули форматирования по умолчанию, можно предоставить список модулей форматирования для ReadAsAsync метод. Instead of using the default formatters, you can provide a list of formatters to the ReadAsAsync method. Использование список модулей форматирования полезно в том случае, если у вас есть модуль форматирования типа мультимедиа. Using a list of formatters is useful if you have a custom media-type formatter:

Отправить запрос POST для создания ресурса Sending a POST Request to Create a Resource

Следующий код отправляет запрос POST, содержащий Product экземпляра в формате JSON: The following code sends a POST request that contains a Product instance in JSON format:

PostAsJsonAsync метод: The PostAsJsonAsync method:

  • Сериализует объект в формат JSON. Serializes an object to JSON.
  • Отправляет полезные данные JSON в запросе POST. Sends the JSON payload in a POST request.

Если запрос выполнен успешно: If the request succeeds:

  • Он должен вернуть ответ 201 (создано). It should return a 201 (Created) response.
  • Ответ должен содержать URL-адрес созданные ресурсы в заголовке Location. The response should include the URL of the created resources in the Location header.

Отправка запроса PUT для обновления ресурса Sending a PUT Request to Update a Resource

Следующий код отправляет запрос PUT для обновления продукта: The following code sends a PUT request to update a product:

PutAsJsonAsync метод работает подобно PostAsJsonAsync, за исключением того, что он отправляет запрос PUT вместо POST. The PutAsJsonAsync method works like PostAsJsonAsync, except that it sends a PUT request instead of POST.

Отправляя запрос DELETE для удаления ресурса Sending a DELETE Request to Delete a Resource

Следующий код отправляет запрос DELETE для удаления продукта: The following code sends a DELETE request to delete a product:

Например GET запрос DELETE не имеет текста запроса. Like GET, a DELETE request does not have a request body. Не нужно указать формат JSON или XML с помощью удаления. You don’t need to specify JSON or XML format with DELETE.

Тестирование образца Test the sample

Чтобы проверить его: To test the client app:

Скачайте и запуск приложения сервера. Download and run the server app. Указания по скачиванию. Download instructions. Убедитесь, что работает серверное приложение. Verify the server app is working. Например http://localhost:64195/api/products должен возвращать список продуктов. For example, http://localhost:64195/api/products should return a list of products.

Задайте базовый URI для HTTP-запросов. Set the base URI for HTTP requests. Измените номер порта к порту, используемому в серверное приложение. Change the port number to the port used in the server app.

Запустите клиентское приложение. Run the client app. Выводятся следующие результаты. The following output is produced:

How to read JSON data in C# (Example using Console app & ASP.NET MVC)?

Now a days JSON is widely used to exchange data due to it’s simplicity and light-weight, so in this article, I am going to provide you with example with code to read JSON data in C#, I will be using ASP.NET MVC and Console appliction example for it.

You can use the C# code for any of your application whether it’s C# console application, windows application or ASP.NET web-application, so in this article, I am going to provide you sample code using ASP.NET MVC & Console application.

Read JSON data in C# in MVC

In this article, i will perform following steps:

  1. Get sample JSON
  2. Create a class file for JSON.
  3. Deserialize JSON using DeserializeObject & save it as step 2creates class list.
  4. Print JSON in the View using Model.

Step 1: Before we proceed for any of the steps, your need to create a ASP.NET MVC sample project in your Visual Studio, so navigate to File-> New -> Project-> Select «Web» from left pane & «ASP.NET web application» (right-pane), name it and Click «OK»

After clikcing OK new windows will appear, let’s select «MVC» template from it to generate basic MVC configuration automatically for our project.


Step 2: Get the sample JSON, here is the sample JSON, which I will be using

Note: You can always validate your JSON using website like JSONLint

Considering above JSON, we can create a C# class to save data in it and then use it as Model and print it in a View.

To do that you can use Visual-studio’s «Paste as Special» feture which is useful to convert, so using the sample provided in the post «Quick Tip to convert JSON into class object», Create a Class «JSONModel.cs» in Models folder of your project and then copy the above sample JSON, navigate to Edit -> Paste Special -> Paste JSON as Classes as shown in the below image.

Then your C# class will be as below

Now, go to your project’s HomeController and inside Index ActionMethod, use the C# code below to Deserialize JSON and convert it into Class Model.

and inside the Index.cshtml view use the Model to get data and print it as HTML.

Build and run it in browser, you will get output as below

Read JSON data in C# using Console Application.

We will be following same procedure as use in MVC project, create a new Console application project by navigating to File -> new-> project -> select «Window Classic desktop» (Left-pane) & «Console App»(from right-pane) , provide and a name («ReadJSONInCharp») and click «OK»

We would have to create class same as JSONModel.cs in MVC project, so right click on your project in the solution, Select «Add»-> Select «Class» , name it as «JSONModel.cs» and use the below C# code

One extra step in this would be to install NewtonSoft.JSON in your project usin Nuget package manager, navigate to «Tools»-> «Nuget Package manager»-> Select «Manage nuget packages for solution. » and click on «Browse» tab, the search «NewtonSoft.JSON» and select it and install in your project

Go to the main Program.cs file and use the code below

Build and run your application, you will get output as below

That’s it we are done, but there can be times when your JSON object is dynamic, so let’s look on another example.

Read Dynamic JSON data in C#

Now, supopose your JSON is dynamic, so you cannot create it’s class, so how you would access it without Model?

I will be using the answer provided in this question here «How to convert dynamic JSON string into C# class?», which looks useful to me, so from the answer, if your JSON is as below

You can Deserliaze it as dynamic object and then access data as you access arrays

There are several other method provided in the above question’s answer, another one is as below

We are done with sample’s, if you have any questions please feel free to comment below.

Calling REST API in C# (Read JSON Data)

Introduction –В REST API using C#

In this post, We will use ZappySys ODBC Powerpack for calling REST API in C# (i.e. CSharp). We will create an ODBC connection to REST API and consume it different ways (e..g Bind API data to Data Grid, Combo Box or Write to File). ZappySys ODBC Driver allows to connect to many other REST API such as Facebook, Google, OneDrive, SharePoint and thousandsВ of other sources that support REST API.

Requirements

  1. First of all, you will needВ ZappySys ODBC PowerPackВ installed. This driver is a very powerful tool to connect with ODBC toВ REST API, JSON files, XML files, WEB API, OData and more.
  2. Secondly, you will need Visual Studio Installed.

Getting Started

Let’s look at few examples to consume REST API or JSON data in C# applications (WPF, Winform, Console App or even Web Application such as ASP.net MVC or Webforms).

Calling REST API in C# to show REST API results in the console

In order to start, we will get the values using REST API. We will use C# toВ get the values. In this example, we will use the following URL to get data:

  1. First of all, we will first create a Visual Studio Windows form using C#.
  2. Secondly, we will add the following code to get the values from the API:


This code connects to ODBC using the ZappySys JSON Driver andВ connection the customers URL:В Also, we open the connection and send the SQL query.В With thisВ query, you can use a simple SQL Query to REST API. Here you have the lists ofВ sentences in SQL supported by the driver:

Finally, we show the information in the console:

C# show rest API information

Here is full C# code to read from REST API in C#. Create a new Console Application Project in Visual Studio (File > New > Project > Visual C# > Console Application )

Calling REST API in C# to show REST API results in a combo box

In the next example, we will show how to call REST API in C# and load theВ data in a combo box. To execute this code you need to create a WinForm Project in Visual StudioВ (File > New > Project > Visual C# > Windows Form Application)

    First of all, in a C# project, add the following code:

Load combo box c# REST API

Calling REST API in C# to show REST API in a Data Grid

The DataGridView is very popular to retrieve data. In this example, we willВ show how to load REST API in the DataGridView.

    First of all, add the following code:

Read from JSON file in C# (Single or Multiple files)

The ZappySys ODBC PowerPack allows connecting not only to REST API, WEB APIВ but also to local files. In this example, we will connect to a file namedВ test.json. Let’s take a look at this example to see how to do it:

    First of all, we will have a JSON file named test.json with thisВ content:

Read JSON file in C#

Calling REST API in C# to get Gmail information

The next example will show how to get Gmail information in C# using RESTВ API.

    First of all, go to the ODBC Administrator in Windows:

Windows ODBC Data Sources

OAuth credential REST API Gmail

Gmail DataGrid View

ZappySys JSON /REST API Driver Query Examples

Reading from XML files or API can be done using the same way as previous sections except you have to use ZappySys XML Driver. Read help file here to see json query examples.

ZappySysВ XML / SOAP Driver Query Examples

Reading from XML files or API can be done using the same way as previous sections except you have to use ZappySys XML Driver. Read help file here to see xml query examples.

Calling XML SOAP Web Service in C#

So far we have looked at examples to consume data using JSON driver. Now lets look at an example, to call XML SOAP Web Service in Qlik.

What is SOAP Web Service?

What is WSDL

Example SQL Query for SOAP API call using ZappySys XML Driver

Video Tutorial — Introduction to SOAP Web Service and SoapUI tool

Preview SOAP API Response / Generate SQL Code for SOAP API Call

Preview Data

Generate Code Option


POST data to REST API URL from file inВ C#

Above example was POST data to API URL but what if your Request Body is large and you have saved that to file? Well here is the way to get your request body from a file (Use @ symbol before path).

Working with JSON in C#

JavaScript Object Notation (JSON) is a way of representing data structures in a “human-readable” form that can be used to exchange information between two different applications. Most commonly this is between client-side JavaScript running in a web browser, and a server-side script running on the web server. Although derived from JavaScript, JSON is a flexible format that can be used with many programming languages.

C# developers have a variety of structures, data formats, and mechanisms they can use to exchange information. The most common use of JSON for them is when communicating with a web service that only accepts and returns data in JSON format. It may be helpful to get an introduction to web APIs before continuing, which will provide background information as to why JSON is used and the benefits of working with web services. A fair amount of experience working with C# is assumed here, so it would be beneficial for beginners to learn programming in C# prior to attempting these techniques.

A Brief Overview of JSON

JSON represents objects in a structured text format, with data stored as key-value (or attribute-value) pairs, an example of which is shown below:

This script block was written for inclusion on a web page, and declares an object representing an entry in a simple address book or contacts list. From JavaScript, you access the information using a dot syntax like udemy.name or udemy.email. The code between the equals sign and the semicolon is what is referred to as JSON.

Because of the flexibility that JavaScript offers, it’s possible to declare a list of objects using one assignment statement:

Notice how square brackets are used to mark the array of objects, and each object is surrounded by curly brackets and separated by a comma.

Unfortunately, the syntax used by JSON is based on JavaScript (which can be interpreted on-the-fly) and cannot be processed the same way by C#.

There are three key methods for working with JSON in C# code:

  • use a free library that can handle most of the work for you;
  • work with DataContracts that are built-in to the .NET framework;
  • or write your own “parser” to convert JSON in strings to a suitable collection of objects.

These methods range from being suitable for beginners, to highly-advanced concepts that should only be attempted by experienced, and knowledgeable, C# programmers.

Using JSON Libraries for C#

This method of working with JSON in your C# applications is, obviously, the easiest. Many free libraries exist that can simplify the process of working with flexible data structures returned in JSON format by a web service. Json.NET and Json-Sharp are two of the most popular.

The basic principle behind using either library is this:

  1. Add the library to your project.
  2. Call a deserialization method from the appropriate converter class.
  3. Pass JSON data in as a String to the converter.
  4. Receive the result as a .NET framework object (usually a collection of some kind).

The code example below uses the Json.NET library to convert the object stored in the string “source” to a .NET framework Dictionary. In this example, source contains the JSON data from the first example in the section “A Brief Overview of JSON” above, which contains a single object.

Dictionary udemy = JsonConvert.DeserializeObject >(source);
System.Diagnostics.Debug.WriteLine(udemy[“name”]);

Json.NET can deserialize to a wide variety of object types, including custom classes. This example deserializes the object to a Dictionary that is defined as having a string for a key, and a string for the value.

For the second example above – an array of objects – you need to tell Json.NET to deserialize to a different object format, for example an array of Dictionary objects:

Serialization using Json.NET is even easier. In this next sample, a Dictionary of strings (similar to the one used above for deserialization) is declared and then serialized to JSON format.

JSON Serialization Using Standard .NET Framework Classes

From .NET Framework v3.5 onwards, Microsoft has included JSON serialization and deserialization in the framework. Unlike the libraries mentioned above, using these classes often requires greater knowledge of the web service you are working with. Because of that, it is a slightly more advanced technique.

Deserialization of JSON-formatted data can be done through classes and methods in the System.Runtime.Serialization and System.Runtime.Serialization.Json libraries. To use them, you must first add a reference to System.Runtime.Serialization in your project, and then define the types of object you will be working with, using DataContract attributes. For example:

The object can then be deserialized using an instance of DataContractJsonSerializer. The following code assumes that the string variable source contains the single object from the first example in the section “A Brief Overview of JSON” above

To deserialize the array of objects from the second example in the section “A Brief Overview of JSON”, the code needs some small alterations. Here you can see how to deserialize to a List of Udemy objects instead:

Serialization is a similarly straightforward process, assuming that you have spent time defining all of the structures and classes that represent the information you need to send to the server:

Writing Your Own JSON Parser

Of course, it’s always possible to write your own code to convert JSON in strings to a form that you can work with in your C# application. However, this can be an extremely difficult process, sharing many similarities with compiler design, and you should give careful thought to whether this is a worthwhile task.

In compiler design, a “lexer” (or lexical analyzer) takes source code in a text file and “parses” it into a hierarchical tree of “tokens”. It has to deal with whitespace issues, checking for errors, and deciding what words or symbols represent in the context of the language. This is very similar to the process you would need to build a JSON parser. With the information parsed to a tree, you would traverse the tree and build up your object’s structure.

Very few people write lexers anymore. Instead, programs called “parser generators” are used to generate source code for a lexer that you can incorporate into your application. For C# developers, CsLex by Brad Merrill can be used to take a specification of the language (written in a text file) and generate C# source code that can understand that language. But that still leaves you with a lot of work to do to actually process the tokens into a usable object, and even writing the language specification file can be a time-consuming and difficult process.


Recommendations

In most cases, using a JSON library will be the easiest way of working with JSON-formatted data in C#. In situations where you don’t want to use a third-party library, and have a good understanding of how data is structured in the web service, using the standard .NET Framework libraries would be a good option.

For more information and practical examples of some of the subjects discussed above, Learn C# 2010 Part III provides a thorough tutorial of using collections, LINQ, and JSON-based web APIs.

C# HttpClient tutorial

C# HttpClient tutorial shows how to create HTTP requests with HttpClient in C#. In the examples, we create simple GET and POST requests.

The Hypertext Transfer Protocol (HTTP) is an application protocol for distributed, collaborative, hypermedia information systems. HTTP is the foundation of data communication for the World Wide Web.

HttpClient is a base class for sending HTTP requests and receiving HTTP responses from a resource identified by a URI.

C# HttpClient status code

HTTP response status codes indicate whether a specific HTTP request has been successfully completed. Responses are grouped in five classes:

  • Informational responses (100–199)
  • Successful responses (200–299)
  • Redirects (300–399)
  • Client errors (400–499)
  • Server errors (500–599)

The example creates a GET request to a small website. We get the status code of the request.

A new HttpClient is created.

The GetAsync() method sends a GET request to the specified Uri as an asynchronous operation. The await operator suspends the evaluation of the enclosing async method until the asynchronous operation completes. When the asynchronous operation completes, the await operator returns the result of the operation, if any.

We get the 200 OK status code; the website is up.

C# HttpClient GET request

The GET method requests a representation of the specified resource.

The example issues a GET request to the webcode.me website. It outputs the simple HTML code of the home page.

The GetStringAsync() sends a GET request to the specified Uri and returns the response body as a string in an asynchronous operation.

This is the output.

C# HttpClient HEAD request

The HTTP HEAD method requests the headers that are returned if the specified resource would be requested with an HTTP GET method.

The example issues a HEAD request.

This are the header fields of the response.

C# HttpClient POST request

The HTTP POST method sends data to the server. The type of the body of the request is indicated by the Content-Type header.

We need to add the Newtonsoft.Json package to process JSON data.

In the example, we send a POST request to https://httpbin.org/post website, which is an online testing service for developers.

We turn an object into a JSON data with the help of the Newtonsoft.Json package.

We send an asynchronous POST request with the PostAsync() method.

We read the returned data and print it to the console.

This is the output.

C# HttpClient JSON request

JSON (JavaScript Object Notation) is a lightweight data-interchange format. This format is easy for humans to read and write and for machines to parse and generate. It is a less verbose and more readable alternative to XML. The official Internet media type for JSON is application/json .

The example generates a GET request to to Github. It finds out the top contributors of the Symfony framework. It uses the Newtonsoft.Json to work with JSON.


In the request header, we specify the user agent.

In the accept header value, we tell that JSON is an acceptable response type.

We generate a request and read the content asynchronously.

We transform the JSON response into a list of Contributor objects with the JsonConvert.DeserializeObject() method.

C# HttpClient download image

The GetByteArrayAsync() sends a GET request to the specified Uri and returns the response body as a byte array in an asynchronous operation.

In the example, we download an image from the webcode.me website. The image is written to the user’s Documents folder.

The GetByteArrayAsync() returns the image as an array of bytes.

We determine the Documents folder with the GetFolderPath() method.

The bytes are written to the disk with the File.WriteAllBytes() method.

C# HttpClient Basic authentication

In HTTP protocol, basic access authentication is a method for an HTTP user agent (such as a web browser or a console application) to provide a user name and password when making a request. In basic HTTP authentication, a request contains a header field in the form of Authorization: Basic , where credentials is the base64 encoding of id and password joined by a single colon : .

HTTP Basic authentication is the simplest technique for enforcing access controls to web resources. It does not require cookies, session identifiers, or login pages; rather, HTTP Basic authentication uses standard fields in the HTTP header.

The example sends credentials to the httpbin.org website.

Here we build the authentication header.

The URL contains authentication details because we test it with the httpbin.org website. This way we don’t need to set up our own server. Authentication details are never put into the URL, of course.

This is the output.

In this tutorial, we have used C# HttpClient to create HTTP requests.

Создание JSON Webservice с использованием C# .NET

Я пытаюсь сделать JSON webservice в C# .NET. Строка JSON возвращается с помощью веб-методы, но он содержит структуру XML, как:

Я видел this статьи, прежде чем это было не очень полезно для меня.

Так что моя проблема в том, что строка json не возвращается в чистом виде. Мне не нужна эта версия xml и xmlns. Я планирую позже использовать веб-сервис на Android.

Может ли кто-нибудь мне помочь?

Создан 29 ноя. 11 2011-11-29 09:29:27 Parth Doshi

Почему вы не используете службы WCF? – Romain Meresse 29 ноя. 11 2011-11-29 09:33:29

Я предпочитаю SOAP, потому что я работал над этим уже давно. Если вы думаете, что WCF — это то, что мне нужно, можете ли вы сказать мне, как мне подключиться к базе данных SQL, запустить запрос select *, получить результат в виде набора данных, преобразовать набор данных в чистый json и затем вернуть его? это было сделано с использованием WCF, потому что я понятия не имею об этом – Parth Doshi 29 ноя. 11 2011-11-29 09:39:16

Я сказал это, потому что я использовал ksoap для потребления многих веб-сервисов на моей стороне клиента.Я хотел, чтобы мой веб-сервис возвратил чистый json, потому что мне трудно даже вернуть json String из моего веб-сервиса. Вы можете увидеть [это] (http://stackoverflow.com/questions/8213654/json-string-returned-from-soap-web-service-containing-no-records-fortable), чтобы лучше понять мою проблему – Parth Doshi 29 ноя. 11 2011-11-29 09:59:01

все ясно, я думаю, что «Json», потому что пакеты WCF больше (как видно в feedler), что делает мобильные приложения. тяжелее. Кроме того, использование технологий без генерации прокси-серверов, таких как службы Ksoap wcf, не дает нам смысла, как обычно используется с Android. (В качестве примечания службы RestFul поддерживают генерацию прокси-сервера, а также для поддержки android + WCF для вывода OData) – Davut Gürbüz 09 окт. 12 2012-10-09 20:26:35

5 ответов

Если вы украшаете свой интерфейс атрибутами для формата запроса и ответа, вы можете получить стандартный WCF для возврата и интерпретации правильного json.

Проблема заключается в том, однако, что врожденная DataContractJsonSerializer WCF в не всегда возвращает правильное JSON. Его сериализация словарей в лучшем случае проблематична, поскольку она сериализована как список пар ключ/значение. Чтобы исправить это, нужно вернуть Stream из методов обслуживания и выполнить сериализацию вручную (используя Json.NET или ServiceStack для выполнения сериализации). В таких случаях, вероятно, целесообразно использовать WebAPI, но для некоторых случаев обычный WCF можно использовать с использованием указанных украшений.

Создан 29 ноя. 11 2011-11-29 09:40:30 faester

Вы можете попробовать построить свою службу, используя REST API. Вы можете найти информацию о REST с WCF по этому адресу link

Вы можете скачать набор инструментов для образцов о том, как создать успокоительные службы wcf, которые возвращают ответ json.

Создан 29 ноя. 11 2011-11-29 09:35:36 Rajesh


WCF Web API стоит изучить, если вы планируете создавать службы REST. Он легко устанавливается через Nuget или из Codeplex

Создан 29 ноя. 11 2011-11-29 09:47:26 Neil Thompson

Это также не проблема при использовании ServiceStack, то есть каждый результат, который вы возвращаете, автоматически преобразуется в требуемом типе Response ContentType, то есть это полный код простого веб-сервиса, который может быть вызван через все HTTP VERBS (GET, POST, PUT, DELETE) во всех поддерживаемых форматах (без необходимости настройки), то есть JSON, XML, HTML, JSV, CSV, SOAP даже прямой HTML-формой x-www- запрос форм-urlencoded или QueryString:

вы можете отменить ответ вы получите с Accept: приложения/JSON Заголовок HTTP или просто добавление ? Format = json в QueryString.

См. ServiceStack’s Hello World Example, чтобы увидеть пример приведенных выше веб-сервисов.

Создан 29 ноя. 11 2011-11-29 22:45:04 mythz

Creating and consuming a web service in C# / .NET

Creating a web service in Visual Studio

Note that in this post I am using the .asmx Web Service as an example, not the newer WCF version.

Create a new Visual Studio project

Right click on the project and select Add > New Item > Web Service (ASMX)

See that the following code gets automatically generated in WebService.asmx.cs

WebService.asmx.cs

On compiling and running the project you are directed to a web browser that points to your service containing the single ‘HelloWorld’ method:

And when you click on the ‘HelloWorld’ link you are directed to the page to invoke the selected operation:

Clicking Invoke then directs you to the XML file:

Add two additional services, Square and SquareRoot to WebService.asmx.cs:

WebService.asmx.cs

Rebuild and re-run your project and notice that two additional services are displayed:

Click on one of the new examples, SquareRoot for example, and invoke this:

Giving use the answer in XML format as shown:

Consuming the web service

Create a new Console Application in your solution

Right click your project and select Add > Service Reference…

Rename the namespace if you wish:

Click on the Advanced button.

Click Add Web Reference

Click the link that says to browse to services in this solution.

Observe that it discovers the web service we earlier created for this solution:

Click on this service and see that the range of service methods is displayed:

Rename the Web reference name to your preference:

Click Add Reference.

Observe the Web References folder containing WebServices is created as shown:

Set the console application as your startup project:

Update Program.cs in your console application to consume the referenced web service.

In this example to find and display the square root of 64:

Program.cs

Giving the following console output when run:

Цукерберг рекомендует:  Полезные заметки serialize или json_encode
Понравилась статья? Поделиться с друзьями:
Все языки программирования для начинающих