【发布时间】: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...:(')
},
});
}
【问题讨论】: