ram kris
ram kris

Reputation: 145

Reading data from json string to c# object

I am developing an Angular App with .net server and the backend is written in c#. I have formed an object by combining the data from two different forms and converted object to json string using JSON.stringify. How can i convert this json string from angular to a c# object and the object should get the values from the json string.

Please guide me. Thanks in Advance.

I used this conversion to convert json string to c# class. UPDATE: Update with controller, signalrhub and cors policy.

json object

const Root = {
    "Unit" : "mm",
    "test": [{
      "Val": this.Val1.isChecked,
      'Val1' : this.val2.isChecked,
    }],
    "test1" :{
      "sub":[{
        'val2' : this.valFormGroup.get('val2').value,
        'Val3' : this.valFormGroup.get('val3').value,
        }]
        },
}
const foo = JSON.stringify(Root);
console.log(foo);

json string.

{"Units":"mm","test":[{"Val":true,"Val1":false}], "test1":[{"Val2":"red","Val3":"5"}]}

c# class

public class Test
{
    public bool Val { get; set; }
    public bool Val1 { get; set; }
}

public class Test1
{
    public string Val2 { get; set; }
    public string Val3 { get; set; }
}

public class RootObject
{
    public string Units { get; set; }
    public List<Test> test { get; set; }
    public List<Test1> test1 { get; set; }
}

Controller

namespace angular.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class DIMController : Controller
    {

             private IHubContext<DIMHub> _hubContext;
        public DIMController(IHubContext<DIMHub> hubContext)
    {
  _hubContext = hubContext;
}
[HttpPost]

 public JsonResult Postdata(string json)
{
 // Your data variable is of type RootObject
 var data= JsonConvert.DeserializeObject<RootObject>(json);

 //Get your variables here as shown in first example. Something like:
 var unit=data.Units; 
 return Json(true);
}  

SignalR hub

namespace angular.HubConfig
{
public class DIMHub: Hub
{
 public async Task Send1 ( string message1, Root data)
{
  await Clients.All.SendAsync("Send1", message1);
}

}
}

Startup.cs

services.AddCors(options =>{
    options.AddPolicy("CorsPolicy",
    builder => builder
    .AllowAnyMethod()
    .AllowAnyHeader()
    .AllowCredentials()
    .AllowAnyOrigin());
app.UseCors("CorsPolicy");
});

Client

form(){
 var json = Root;
  $.ajax({
    type: "POST",
    cache: false,  
    dataType: "json",
    url: 'http://localhost:5001/api/DIM/Postdata',     
    data: { "json": JSON.stringify(json)},  
   // contentType: "application/json",    

  // headers : {'Content-Type': 'application/json'},
  success: function (data) {
    console.log(data)
  },
  error: function (data) {
    console.log('error in sending data...:(')
  },
  });
}

Upvotes: 2

Views: 1222

Answers (5)

Ronil Lakhani
Ronil Lakhani

Reputation: 1

try this one

var obj=JSON.parse("yourjsonstring")

console.log(obj);

Upvotes: -1

Rahul Sharma
Rahul Sharma

Reputation: 8312

Your model classes are correct in accordance to your JSON string that you have posted in the question. All you would require is to deserialize the string correctly. I am posting a code snippet specifically for your JSON string. I am using the Newtonsoft JSON library which is a popular high-performance JSON framework for .NET.

A working demo: https://dotnetfiddle.net/s2OXhT

using System;
using Newtonsoft.Json;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        var jsonString = @"{'Units':'mm','test':[{'Val':true,'Val1':false}], 'test1':[{'Val2':'red','Val3':'5'}]}";
        var data= JsonConvert.DeserializeObject<RootObject>(jsonString);
        Console.WriteLine(data.Units);

        foreach(var values in data.test)
        {
            Console.WriteLine(values.Val);  
            Console.WriteLine(values.Val1);
        }

        foreach(var values1 in data.test1)
        {
            Console.WriteLine(values1.Val2);    
            Console.WriteLine(values1.Val3);
        }       
    }
}

public class Test
{
    public bool Val { get; set; }
    public bool Val1 { get; set; }
}

public class Test1
{
    public string Val2 { get; set; }
    public string Val3 { get; set; }
}

public class RootObject
{
    public string Units { get; set; }
    public List<Test> test { get; set; }
    public List<Test1> test1 { get; set; }
}

Output:

mm
True
False
red
5

Update: In the above part, I have given you an example of how to deserialize your JSON string correctly. In the example below, I am giving a very basic example of how you can use AJAX to post your values as a JSON string to your Controller method. I am not very familiar with Angular so I will try my best here:

Your AJAX call would look like:

<script type="text/javascript">

const Root = {
    "Unit" : "mm",
    "test": [{
      "Val": this.Val1.isChecked,
      'Val1' : this.val2.isChecked,
    }],
    "test1" :{
      "sub":[{
        'val2' : this.valFormGroup.get('val2').value,
        'Val3' : this.valFormGroup.get('val3').value,
        }]
        },
     }

var json = Root;

//Assuming a button click event here but you can use any event 
$('#myBtn').click(function (){
    $.ajax({
        url: '@Url.Action("ProcessJSON", "Home")', // This can be a WEB API method or a Controller method. You can even call 3rd party WEB API  
        type: "POST",
        dataType: "json",
        data: { "json": JSON.stringify(json)},
        success: function (data) {
           console.log(data)
         },
         error: function (data) {
           console.log('error in sending data...:(')
         },
    });
};
</script>

Your Controller would look like something like this:

[HttpPost]
public JsonResult ProcessJSON(string json)
{
 // Your data variable is of type RootObject
 var data= JsonConvert.DeserializeObject<RootObject>(json);

 //Get your variables here as shown in first example. Something like:
 var unit=data.Units; //mm

 return Json(true);
}

Upvotes: 2

Fatih G&#220;RDAL
Fatih G&#220;RDAL

Reputation: 1519

Using ASP.NET Web Api Project

You used Root>test1 in "sub" property.

Javascript

    var Root = {
        "Unit" : "mm",
        "test": [{
          "Val": this.Val1.isChecked,
          'Val1' : this.val2.isChecked,
        }],
        "test1" :{
          "sub":[{
            'val2' : this.valFormGroup.get('val2').value,
            'Val3' : this.valFormGroup.get('val3').value,
            }]
            },
    }

 $.ajax({
        type: "POST",
        url: 'http://YouSite/api/controller/YouActionName',        
        data: Root ,
        dataType: "json",
        headers : {'Content-Type': 'application/json'},
        success: function (data) {
           console.log("Message: ",data.Message);
           console.log("Status: ", data.MyStatus);
         },
         error: function (data) {
           console.warn(data);
         },
    });

OUTPUT

Message:  transaction successful
Status:  true

ASP.NET Web Api Controller

ASP.NET WebApi automatically serializes json data

[HttpPost]
public MyResponseModel YouActionName([FromBody]MyRootObject data)
{
 var unit=data.Unit;
 var test=data.test;
 var subs=data.test1.sub;
var response = new MyResponseModel(){ Message="transaction successful", MyStatus=true};
//you can customize your return object
 return response;
}

Web Api Route

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                "DefaultApi",
                "api/{controller}/{action}/{id}",
                new {id = RouteParameter.Optional}
            );
        }
    }

Request Models

  public class Test
    {
        public bool Val { get; set; }
        public bool Val1 { get; set; }
    }

    public class Test1
    {
        public List<Sub> sub { get; set; }
    }
    public class Sub
    {
        public string Val2 { get; set; }
        public string Val3 { get; set; }
    }

    public class RootObject
    {
        public string Units { get; set; }
        public List<Test> test { get; set; }
        public List<Test1> test1 { get; set; }
    }

Response Model

 public class MyResponseModel
    {
        public string Message { get; set; }
        public bool MyStatus { get; set; }
    }

Upvotes: 1

Adrita Sharma
Adrita Sharma

Reputation: 22213

Try like this:

jsonString = {"Units":"mm","test":[{"Val":true,"Val1":false}], "test1":[{"Val2":"red","Val3":"5"}]}

var data= JsonConvert.DeserializeObject<RootObject>(jsonString);

Upvotes: 1

Jens Alenius
Jens Alenius

Reputation: 1931

If you setup an ASP .NET CORE Webapi it more or less does it for you.

https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-2.2&tabs=visual-studio Checkout section: Add a Create method

Upvotes: 2

Related Questions