I often need to extend my Domain model with additional info before returning it to the client with WebAPI. To avoid creation of ViewModel I thought I could return JObject with additional properties. I could not however find direct way to convert object of any type to JObject with single call to Newtonsoft JSON library. I came up with something like this:
Eg.:
var cycles = cycleSource.AllCycles();
var settings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
var vm = new JArray();
foreach (var cycle in cycles)
{
var cycleJson = JObject.Parse(JsonConvert.SerializeObject(cycle, settings));
// extend cycleJson ......
vm.Add(cycleJson);
}
return vm;
I this correct way ?
JObject implements IDictionary, so you can use it that way. For ex,
var cycleJson = JObject.Parse(@"{""name"":""john""}");
//add surname
cycleJson["surname"] = "doe";
//add a complex object
cycleJson["complexObj"] = JObject.FromObject(new { id = 1, name = "test" });
So the final json will be
{
"name": "john",
"surname": "doe",
"complexObj": {
"id": 1,
"name": "test"
}
}
You can also use dynamic
keyword
dynamic cycleJson = JObject.Parse(@"{""name"":""john""}");
cycleJson.surname = "doe";
cycleJson.complexObj = JObject.FromObject(new { id = 1, name = "test" });