我经常需要使用其他信息扩展我的域模型,然后再使用WebAPI将其返回给客户端。为了避免创建ViewModel,我想我可以使用其他属性返回JObject。然而,我无法通过单次调用Newtonsoft JSON库找到将任何类型的对象转换为JObject的直接方法。我想出了类似的东西:
例如:
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;
我这是正确的方法吗?
答案 0 :(得分:103)
JObject实现了IDictionary,因此你可以这样使用它。例如,
var cycleJson = JObject.Parse(@"{""name"":""john""}");
//add surname
cycleJson["surname"] = "doe";
//add a complex object
cycleJson["complexObj"] = JObject.FromObject(new { id = 1, name = "test" });
所以最终的json将是
{
"name": "john",
"surname": "doe",
"complexObj": {
"id": 1,
"name": "test"
}
}
您还可以使用dynamic
关键字
dynamic cycleJson = JObject.Parse(@"{""name"":""john""}");
cycleJson.surname = "doe";
cycleJson.complexObj = JObject.FromObject(new { id = 1, name = "test" });
答案 1 :(得分:19)
如果你有一个对象并希望成为JObject,你可以使用:
JObject o = (JObject)JToken.FromObject(miObjetoEspecial);
像这样:
Pocion pocionDeVida = new Pocion{
tipo = "vida",
duracion = 32,
};
JObject o = (JObject)JToken.FromObject(pocionDeVida);
Console.WriteLine(o.ToString());
// {"tipo": "vida", "duracion": 32,}
答案 2 :(得分:0)
这将有效:
var cycles = cycleSource.AllCycles();
var settings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
var vm = new JArray();
foreach (var cycle in cycles)
{
var cycleJson = JObject.FromObject(cycle);
// extend cycleJson ......
vm.Add(cycleJson);
}
return vm;