如何从c#类序列化为JSON
在ASP.NET MVC中,我使用C#使用VS菜单编辑>粘贴特殊>粘贴Json作为类,从Json模型派生出以下类。 我想应用我自己的数据。如何创建我的数据模型,而不是使用Rootobject obj=new Rootobject{properties here…},这样我就可以将其序列化到视图控制器中?例如,有没有更好的方法可以用EF来实现如何从c#类序列化为JSON,c#,json,asp.net-mvc,C#,Json,Asp.net Mvc,在ASP.NET MVC中,我使用C#使用VS菜单编辑>粘贴特殊>粘贴Json作为类,从Json模型派生出以下类。 我想应用我自己的数据。如何创建我的数据模型,而不是使用Rootobject obj=new Rootobject{properties here…},这样我就可以将其序列化到视图控制器中?例如,有没有更好的方法可以用EF来实现 public class Rootobject { public string MerchantOrderId { get; set; }
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
});
至于序列化,newtonsoft站点很好地涵盖了这一点:我不确定问题的视图部分正是这样做的(默认情况下,它使用的是
JavascriptSerializer
,而不是JSON.Net
)-您遇到了什么问题?@Ryan这些示例中的问题是,它们将模型数据生成到数组(列表)中,在本例中显示[]但是我的问题中提供的模型不包含数组。@Stephen我编辑了我的问题。@Stephen,关于使用JSON.NET,您是对的,谢谢!谢谢@Saeed,但我想使用另一种方法,例如Json自定义obj或其他任何方法。我会尝试一下。非常感谢。