在将其返回到使用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;
Run Code Online (Sandbox Code Playgroud)
我这是正确的方法吗?
L.B*_*L.B 111
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" });
Run Code Online (Sandbox Code Playgroud)
所以最终的json将是
{
"name": "john",
"surname": "doe",
"complexObj": {
"id": 1,
"name": "test"
}
}
Run Code Online (Sandbox Code Playgroud)
您也可以使用dynamic
关键字
dynamic cycleJson = JObject.Parse(@"{""name"":""john""}");
cycleJson.surname = "doe";
cycleJson.complexObj = JObject.FromObject(new { id = 1, name = "test" });
Run Code Online (Sandbox Code Playgroud)
Con*_*dua 21
如果你有一个对象并希望成为JObject,你可以使用:
JObject o = (JObject)JToken.FromObject(miObjetoEspecial);
Run Code Online (Sandbox Code Playgroud)
像这样 :
Pocion pocionDeVida = new Pocion{
tipo = "vida",
duracion = 32,
};
JObject o = (JObject)JToken.FromObject(pocionDeVida);
Console.WriteLine(o.ToString());
// {"tipo": "vida", "duracion": 32,}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
97693 次 |
最近记录: |