如何使用 .NET 将多个 C# 类序列化为一个 JSON 字符串,使得 JSON 数据中的变量能够保存可变值。
代码示例:
string outputJSON = JsonConvert.SerializeObject();
以下是需要序列化的类:
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结构,我必须能够捕获用户输入并将值设置到json文件中。
{
"Number": "xTest",
"RequestedDeviceType": "XXXX",
"DeliveryMethod": "XXXX",
"Customer": {
"Contacts": {
"FirstName": "John",
"Name": "Doe",
"Email": "mail@demo.com",
"City": "Harare",
"Address": "XXXXX",
"MobilePhone": "00000000"
},
"Name": "Peter Chaneta",
"Number": "4567865678",
"OverrideData": true
},
"Vehicle": {
"VIN": "weryts55444554",
"MakeModelCode": "34010",
"LicensePlate": "SS 100 GP",
"Make": "RANGE ROVER",
"Model": "SPORT",
"YearOfInitialRegistration": 2016,
"MotorType": "Petrol",
"OverrideData": true
}
}
string output = JsonConvert.SerializeObject(yourobject);
这句代码的作用是将你的对象序列化为 JSON 字符串。JSON 表示方式反映了你的类组成,这就是它的工作。 - haronaut