我想使用任意字段序列化和反序列化对象。我尝试将具有任意字段的对象扩展为Dictionary<string, object>
,以期能够将任意字段设置为Dictionary条目。在这种情况下,除了Company
和Position
字段之外,我希望json响应中(在代码注释中列出)还有manager
和office
。不幸的是,我可以获取任意字段,但无法获取非任意字段。
我还希望能够添加任意对象,而不仅仅是字符串(即向工作添加基本工资,奖金等的薪水对象)。我也有一些限制,因此不能使用dynamic
。
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Job Job { get; set; }
}
public class Job : Dictionary<string, object>
{
public string Company { get; set; }
public string Position { get; set; }
}
var job = new Job()
{
Company = "Super Mart",
Position = "Cashier"
};
// Set arbitrary fields
job["manager"] = "Kathy";
job["office"] = "001";
var john = new Person()
{
Name = "John Doe",
Age = 41,
Job = job
};
var employeeJson = JsonConvert.SerializeObject(john, Formatting.Indented);
Log.Debug("TestSerialization", "json: {0}", employeeJson);
// Result
// {
// "Name": "John Doe",
// "Age": 41,
// "Job": {
// "manager": "Kathy",
// "office": "001"
// }
// }
var johnDoe = JsonConvert.DeserializeObject<Person>(employeeJson);
Log.Debug("TestSerialization", "name: {0}, age: {1}", johnDoe.Name, johnDoe.Age);
// Result
// name: John Doe, age: 41
Log.Debug("TestSerialization", "company: {0}, position: {1}", johnDoe.Job.Company, johnDoe.Job.Position);
// Result
// company: , position:
Log.Debug("TestSerialization", "manager: {0}, office: {1}", johnDoe.Job["manager"], johnDoe.Job["office"]);
// Result
// manager: Kathy, office: 001
我使用此代码进行反序列化的结果json是
{
"Name": "John Doe",
"Age": 41,
"Job": {
"manager": "Kathy",
"office": "001"
}
}
我希望结果json是(服务期望的)
{
"Name": "John Doe",
"Age": 41,
"Job": {
"Company" = "Super Mart",
"Position" = "Cashier"
"manager": "Kathy",
"office": "001"
}
}
答案 0 :(得分:1)
我认为您的工作类别有问题,它是从词典派生的,因此在序列化时将不考虑其成员。仅字典值,
尝试这种方式,我不确定这是否会帮助您解决问题
public class Job
{
public string Company { get; set; }
public string Position { get; set; }
public Dictionary<string,object> job { get; set; }
public Job()
{
job = new Dictionary<string, object>();
}
}
Debug.Log(johnDoe.Job.job [“ manager”] +“-” + johnDoe.Job.job [“ office”]);