How to Convert JSON Object to XML in C#

JSON (Javascript Object Notation) is very popular for web development. It is light weight data-exchange format. Most of the applications are using this format to exchange the data for web applications.


Sample JSON array of Objects : 

{
  "users": [
      {"firstName":"John""lastName":"Peter"},
      {"firstName":"Wills""lastName":"Smith"}
    ]
}


To use this format, need to install the Newtonsoft.json package. For more detail and version related information you can find it ✋here.

Open the Visual Studio, go to the package manager console and type the below command.



Basic Definition of XML (Extensible Markup Language is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable.

Sample XML format : 

<root>
  <user>
      <firstName>John</firstName>
      <lastName>Peter</lastName>   </user>
  <user>
      <firstName>Hays</firstName>
      <lastName>Rond</lastName>   </user>
</root>


Create a example to pass JSON object from Angular and convert into XML string in C# and stored that XML formatted data in SQL database.

Sometimes will try to store the normal formatted XML string with some special characters like              ( &, +, -, /, \ ) SQL will not support to store directly it will throws an exception. To Overcome this type of issues, need to create a JSON object and Deserialize into XML Nodes.


Step 1 : Create a new angular application.

Step 2 : Import the HttpClient module in the app.module.ts.

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    CommonModule,
    HttpClient
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


Step 3 : In AppComponent, use below code to send the POST request.

import { HttpClient } from '@angular/common/http';
import { ComponentOnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

  constructor(public httpServiceHttpClient) { }

  public ngOnInit(): void {

    const usersList = [
      {
        firstName: 'John',
        lastName: 'Smith',
        email: 'johnsmith@db.com'
      },
      {
        firstName: 'Peter',
        lastName: 'Wills',
        email: 'peterwills@db.com'
      },
      {
        firstName: 'William',
        lastName: 'Kear',
        email: 'williamkear@db.com'
      }
    ];

    const sampleUsersJsonArrayObject = { userInformation: usersList };

    this.httpService.post('https://sendtoserver.com/createusers'            sampleUsersJsonArrayObject).subscribe(data => {
      // result from the server
    });
  }

}


Above code will sends the array of objects data in JSON format to API.

Now, we will create API and add controller and add new HttpPost method to receive the data.




Expected result format looks below : 

<root>
  <userInformation>
    <firstName>John</firstName>
    <lastName>Smith</lastName>
    <email>johnsmith@db.com</email>
  </userInformation>
  <userInformation>
    <firstName>Peter</firstName>
    <lastName>Wills</lastName>
    <email>peterwills@db.com</email>
  </userInformation>  
  <userInformation>
    <firstName>William</firstName>
    <lastName>Kear</lastName>
    <email>williamkear@db.com</email>
  </userInformation>
</root>


Comments

Popular posts from this blog

How To Setup Angular 10 Environment On Windows

Create Custom Form Control for ng-select in Angular

Angular CLI Commands - Cheat Sheet

Difference of High-Level Design (HLD) and Low-Level Design (LLD)

Configure the API gateway in Microservices Architecture with example in .NET Core

Domain Driven Design (DDD) in .NET Core

Recommended Visual Studio Code Extensions for Angular Development

Send API POST Request in MS SQL Server

Tightly Coupled and Loosely Coupled in .NET Core with example

Export to Excel in Angular 6 | 7 | 8 | 9 | 10