将C#类序列化为json

时间:2017-10-30 12:38:18

标签: c# json serialization

我有以下代码必须将c#类序列化为Json对象。问题是我不能让其他类被序列化,一个去。如何将变量数据分配给所有其他类,以便我可以将它们序列化为一个json文件。

static void Main(string[] args)
{
   Rootobject data = new Rootobject();

   var dataString = JsonConvert.SerializeObject(data);

   File.WriteAllText("Output.json", dataString);
}

public class Rootobject
{
   public string Number { get; set; }

   public string RequestedDeviceType { get; set; }

   public string DeliveryMethod { get; set; }

   public Customer Customer { get; set; }

   public Vehicle Vehicle { get; set; }
}

public class Customer
{
   public Contacts Contacts { get; set; }

   public string Name { get; set; }

   public string Number { get; set; }

   public bool OverrideData { get; set; }
}

public class Contacts
{
   public string FirstName { get; set; }

   public string Name { get; set; }

   public string Email { get; set; }

   public string City { get; set; }

   public string Address { get; set; }

   public string MobilePhone { get; set; }
}

public class Vehicle
{
   public string VIN { get; set; }

   public string MakeModelCode { get; set; }

   public string LicensePlate { get; set; }

   public string Make { get; set; }

   public string Model { get; set; }

   public int YearOfInitialRegistration { get; set; }

   public string MotorType { get; set; }

   public bool OverrideData { get; set; }
}

序列化后我的Json输出应如下所示

{
   "Number": "DTY28968YU",
   "RequestedDeviceType": "MHubObd",
   "DeliveryMethod": "ByHand",
   "Customer": {
      "Contacts": {
         "FirstName": "Mike",
         "Name": "Paul",
         "Email": "mail@demo.com",
         "City": "San Luis",
         "Address": "No 10 Highway Road , San Luis",
         "MobilePhone": "+54000000000"

      },
      "Name": "John Doe",
      "Number": "PolicyNumber24",
      "OverrideData": true
   },
   "Vehicle": {
      "VIN": "VIN004001",
      "MakeModelCode": "34010",
      "LicensePlate": "SS 100 GP",
      "Make": "RANGE ROVER",
      "Model": "SPORT",
      "YearOfInitialRegistration": 2016,
      "MotorType": "Petrol",
      "OverrideData": true
   }
}

1 个答案:

答案 0 :(得分:0)

您只需要实例化该数据。例如:

var r = new Rootobject();
r.Customer = new Customer { Name = "John Doe", Number="PolicyNumber24", 
    OverrideData=true};
var dataString = JsonConvert.SerializeObject(r);

同时实例化其他类,您的序列化也应该有效。