JObject实现了IDictionary,所以您可以用这种方式使用它。例如
在使用WebAPI将域模型返回给客户端之前,我经常需要使用其他信息来扩展域模型。为了避免创建ViewModel,我想我可以返回带有附加属性的JObject。然而,我找不到直接的方法来将任何类型的对象转换为JObject,只需调用Newtonsoft JSON库。我想出了这样的东西:
- 第一个SerializeObject
- 然后分析
- 并扩展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;
我这样做对吗?
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" });
如果您有一个对象并希望成为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,}
这将起作用:
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;
JObject.FromObject(obj);
此处的文档