I am using NewtonJson for serializing object. I want to serlize a object which has two properties one is normal string and the second property is dictionary of some items.
I am expecting a result something like this:
"Company": {
"Id": "1393",
"emp1": {
"email": "[email protected]",
"firstName": "test1",
"lastName": "test1",
"title": "Mr"
},
"emp2": {
"email": "[email protected]",
"firstName": "test2",
"lastName": "test2",
"title": "Ms"
}
}
but I am getting output like below:
"Company": {
"Id": "1393",
"employees": {
"emp1": {
"email": "[email protected]",
"firstName": "test1",
"lastName": "test1",
"title": "Mr"
},
"emp2": {
"email": "[email protected]",
"firstName": "test2",
"lastName": "test2",
"title": "Ms"
}
}
}
Here is my Code:
public string GetCompany(Dictionary<string, Employee> employees)
{
var company = JsonConvert.SerializeObject(new
{
Id = "1393",
employees
});
return company;
}
3
Answers
By creating the anonymous object, your adding another property named
employees
.Why not just append
Id
to the dictionary?e.g.
This makes a copy of
employees
and adds a new key"Id"
before serialising.Create a Poco (Plain Old C# Object). Make sure to add
[JsonExtensionData]
attribute.And then serialize it
Unfortunately it is not clear what is your goal. If you just need a json string , you can try this code
but probably you need something bigger, so maybe it makes some sense to create a JObject in order to add it to another part of you data. In the end you can serialize it calling ToString() function