【问题标题】:Reading data from json string to c# object从 json 字符串读取数据到 c# 对象
【发布时间】:2022-03-05 13:07:38
【问题描述】:

我正在开发一个带有 .net 服务器的 Angular 应用程序,后端是用 c# 编写的。我通过组合来自两种不同形式的数据并使用 JSON.stringify 将对象转换为 json 字符串来形成一个对象。如何将此 json 字符串从 angular 转换为 c# 对象,并且该对象应从 json 字符串中获取值。

请指导我。提前致谢。

我使用conversion 将 json 字符串转换为 c# 类。 更新: 更新控制器、signalrhub 和 cors 政策。

json 对象

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 字符串。

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

c#类

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; }
}

控制器

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 集线器

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");
});

客户

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...:(')
  },
  });
}

【问题讨论】:

    标签: c# .net angular


    【解决方案1】:

    如果您设置了 ASP .NET CORE Webapi,它或多或少会为您完成。

    https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-2.2&tabs=visual-studio 结帐部分:添加 Create 方法

    【讨论】:

      【解决方案2】:

      根据您在问题中发布的JSON 字符串,您的模型类是正确的。您所需要的只是正确反序列化字符串。我正在为您的JSON 字符串发布一个代码 sn-p。我正在使用 Newtonsoft JSON 库,它是一个流行的 .NET 高性能 JSON 框架。

      一个工作演示: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; }
      }
      

      输出:

      mm
      True
      False
      red
      5
      

      更新: 在上面的部分中,我给了你一个如何正确反序列化 JSON 字符串的例子。在下面的示例中,我给出了一个非常基本的示例,说明如何使用AJAX 将您的值作为JSON 字符串发布到您的Controller 方法。我对 Angular 不是很熟悉,所以我会在这里尽力而为:

      您的AJAX 电话如下所示:

      <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>
      

      您的Controller 看起来像这样:

      [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);
      }
      

      【讨论】:

      • 您能否建议我如何将 jsonsting 从 Angular 客户端导入到 c# 对象。我的 jsonstring 在 appcomponent.ts 中。
      • @ramkris 为此,您需要设置一个 Web 方法,将这个 JSON 字符串作为有效负载处理。您可以使用 AJAX 通过 Angular 客户端发送您的 json 字符串。
      • 感谢您抽空拉胡尔。我去看看。
      • @ramkris 我将用一个非常基本的示例来更新我的答案,说明如何实现这一目标。
      • 我没试过。我正在研究其他问题。我会在尝试解决方案后立即更新。非常感谢您的提问。
      【解决方案3】:

      试试这样:

      jsonString = {"Units":"mm","test":[{"Val":true,"Val1":false}], "test1":[{"Val2":"red","Val3":"5"}]}
      
      var data= JsonConvert.DeserializeObject<RootObject>(jsonString);
      

      【讨论】:

        【解决方案4】:

        使用ASP.NET Web Api项目

        您在“sub”属性中使用了 Root>test1。

        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);
                 },
            });
        

        输出

        Message:  transaction successful
        Status:  true
        

        ASP.NET Web Api 控制器

        ASP.NET WebApi 自动序列化 json 数据

        [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 路由

        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}
                    );
                }
            }
        

        请求模型

          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; }
            }
        

        响应模型

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

        【讨论】:

        • 嗨@Faith,我已经尝试过你的解决方案,但我收到错误“OPTIONS localhost:5001/api/Ds/post net::ERR_EMPTY_RESPONSE zone.js:3331”。你能指导我吗?
        • @ramkris 需要查看代码。此错误与我的解决方案无关。可能是您请求的地址或您错过的设置。把你的整个项目上传到github,我们来看看吧。
        【解决方案5】:

        试试这个

        var obj=JSON.parse("yourjsonstring")
        
        console.log(obj);
        

        【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多