I'd like to serialize and deserialize objects with arbitrary fields. I've tried to have the object with the arbitrary fields extend Dictionary<string, object> in hopes that I would be able to set the arbitrary fields as Dictionary entries. In this case I expect to have Company and Position in the json response (listed in code comments) in addition to the manager and office fields. Unfortunately I'm able get the arbitrary fields but unable to get the non arbitrary fields.
I would also like to be able to add arbitrary objects, not just strings (ie add a salary object with base salary, bonus, etc to the job). I also have some restrictions and cannot use dynamic for this.
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
My result json from deserialization using this code is
{
"Name": "John Doe",
"Age": 41,
"Job": {
"manager": "Kathy",
"office": "001"
}
}
I would like the result json to be (what the service would expect)
{
"Name": "John Doe",
"Age": 41,
"Job": {
"Company" = "Super Mart",
"Position" = "Cashier"
"manager": "Kathy",
"office": "001"
}
}
companyandposition- the two non arbitrary fields in theJobmodel to not be null.