首页 > 解决方案 > 如何从 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);

任何帮助将不胜感激!

标签: c#jsonasp.net-mvc

解决方案


尝试这个:

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
    });

推荐阅读