c# - 如何从 c# 类序列化为 JSON
问题描述
我在 ASP.NET MVC 中有以下类,使用从 Json 模型派生的 C#,使用 VS 菜单编辑 > 选择性粘贴 > 将 Json 粘贴为类。我想应用我自己的数据。如何创建我的数据模型,而不是使用 Rootobject obj = new Rootobject { properties here....},以便我可以将其序列化为 View Controller?例如,有没有更好的方法来使用 EF 呢?
public class Rootobject
{
public string MerchantOrderId { get; set; }
public Customer Customer { get; set; }
public Payment Payment { get; set; }
}
public class Customer
{
public string Name { get; set; }
}
public class Payment
{
public string Type { get; set; }
public bool Authenticate { get; set; }
public int Amount { get; set; }
public string ReturnUrl { get; set; }
public Debitcard DebitCard { get; set; }
}
public class Debitcard
{
public string CardNumber { get; set; }
public string Holder { get; set; }
public string ExpirationDate { get; set; }
public string SecurityCode { get; set; }
public string Brand { get; set; }
}
我想将它序列化为 Json 作为下面的相同输出,但使用上面生成的类中的我自己的数据:
{
"MerchantOrderId":"2014121201",
"Customer":{
"Name":"Comprador Cartão de débito"
},
"Payment":{
"Type":"DebitCard",
"Authenticate": true,
"Amount":15700,
"ReturnUrl":"http://www.cielo.com.br",
"DebitCard":{
"CardNumber":"4551870000000183",
"Holder":"Teste Holder",
"ExpirationDate":"12/2030",
"SecurityCode":"123",
"Brand":"Visa"
}
}
}
使用表达式进入视图控制器:
return Json(MyModel, JsonRequestBehavior.AllowGet);
任何帮助将不胜感激!
解决方案
尝试这个:
1.在控制器中
public ActionResult ....()
{
var rootobject =new Rootobject();
//set values
...
...
return Json(new
{
Rootobject= rootobject
});
}
2.在js中
$.ajax({
type: 'POST',
url: //url,
dataType: 'json',
data: {
},
error: function (err) {
},
success: function (data) {
var rootobject =data.Rootobject;
...
...
},
async: true
});
推荐阅读
- java - 如何存储在数据库中创建的 Trie 数据结构并在生产中实现到大型系统?
- c# - 无法使用 websocket 在 C# 中连接槽代理
- android - 未找到:“dart:html”导入“dart:html”;我不需要 dart:html 我也没有使用过,但我尝试通过导入它,但错误不会发生
- flutter - 颤振 | 本地通知:ZonedSchedule 只触发一次
- r - 这个 ifelse 命令有什么问题?(排除与 if 语句不匹配的行)
- python - 如何在python中找到wav文件的幅度?
- wpf - wpf xaml PathGeometry BezierSegment
- c - 如何将 asm() 与 const char* 一起使用而不是字符串文字?
- c# - 设置时模拟未按预期运行
- c# - 设计通用产品处理器