使用Json.NET将任何类型的对象转换为JObject

ycggw6v2  于 2023-02-10  发布在  .NET
关注(0)|答案(4)|浏览(253)

在使用WebAPI将域模型返回给客户端之前,我经常需要使用附加信息扩展域模型。为了避免创建ViewModel,我想我可以返回带有附加属性的JObject。然而,我无法找到直接的方法,通过调用Newtonsoft JSON库将任何类型的对象转换为JObject。我想出了类似以下的方法:
1.第一个序列化对象
1.然后分析
1.并扩展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;

我这条路对吗?

rxztt3cl

rxztt3cl1#

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" });
63lcw9qa

63lcw9qa2#

如果您有一个对象并希望成为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,}
8e2ybdfx

8e2ybdfx3#

这将工作:

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;
ovfsdjhp

ovfsdjhp4#

JObject.FromObject(obj);

文件here

相关问题