【发布时间】:2018-05-13 06:18:22
【问题描述】:
我在 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);
任何帮助将不胜感激!
【问题讨论】:
-
至于序列化,newtonsoft 网站很好地涵盖了这一点:newtonsoft.com/json/help/html/SerializingJSON.htm 我不确定问题的查看部分。
-
您的
return Json(...);正是这样做的(除了默认使用JavascriptSerializer,而不是JSON.Net) - 你有什么问题? -
@Ryan 这些示例中的问题是它们将模型数据生成到数组( List )中,在这种情况下将 [] 显示为 JSON,但我的问题中提供的模型不包含数组。
-
@Stephen 我编辑了我的问题。
-
@Stephen,您使用 JSON.NET 是对的,谢谢!
标签: c# json asp.net-mvc