Reputation: 1138
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"
}
}
Upvotes: 0
Views: 209
Reputation: 175
I think the problem with your job Class, it derived from a dictionary so when you serialize it will not consider its members. only dictionary values,
Try this way, I am not sure this will help your context
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"]);
Upvotes: 1