gpt4 book ai didi

c# - 从json字符串读取数据到c#对象

转载 作者:行者123 更新时间:2023-11-30 20:14:57 24 4
gpt4 key购买 nike

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

请指导我。提前致谢。

我用过这个conversion将 json 字符串转换为 C# 类。更新:使用 Controller 、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; }
}

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

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

}
}

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

最佳答案

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

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

关于c# - 从json字符串读取数据到c#对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57972988/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com