且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-01-17 23:21:47

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