本文介绍了转换任何类型的对象JObject与Json.NET的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常需要它的WebAPI返回到客户端之前致以带有附加信息的域模型。为了避免视图模型的创建,我想我可以与附加属性返回JObject。我无法找到不过直接的方式向任何类型的对象转换为JObject一起Newtonsoft JSON库单呼。我想出了这样的事情:

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:


  1. 第一SerializeObject

  2. 然后解析

  3. 和扩展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;



我这个正确的方法?

I this correct way ?

推荐答案

JObject实现IDictionary的,所以你可以使用这种方式。对于恩,

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



所以最终的JSON将

So the final json will be

{
  "name": "john",
  "surname": "doe",
  "complexObj": {
    "id": 1,
    "name": "test"
  }
}

您也可以使用动态关键字

dynamic cycleJson  = JObject.Parse(@"{""name"":""john""}");
cycleJson.surname = "doe";
cycleJson.complexObj = JObject.FromObject(new { id = 1, name = "test" });

这篇关于转换任何类型的对象JObject与Json.NET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 10:36