C# 如何使用 json.net 将 json 数组添加到 JObject 的属性中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15824194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 18:04:51  来源:igfitidea点击:

How to add a json array into a property of a JObject with json.net

c#jsonserializationjson.netdeserialization

提问by bruchowski

I am having difficulty figuring out how to add an array of json objects to an existing JObject. Say I have a JObjectwith just the "Modified" property, and I want to add another property "IntersectGroups" that contains an array of json objects, how can I do this? I Have a JObject[]that when I serialize it is exactly in the format I require, but I am looking for something like this: mainJObject.Add("IntersectGroups", myJObjectArray)

我很难弄清楚如何将一组 json 对象添加到现有的JObject. 假设我只有一个JObject“修改”属性,我想添加另一个包含一组 json 对象的属性“IntersectGroups”,我该怎么做?我有一个JObject[],当我序列化它时它正是我需要的格式,但我正在寻找这样的东西:mainJObject.Add("IntersectGroups", myJObjectArray)

Here is an example of the final json I want when I serialize it.

这是我在序列化它时想要的最终 json 的示例。

...
"Modified": "2012-11-26T10:21:04.693",
"IntersectGroups": [
  {
    "Id": 1004,
    "UserId": 20003,
    "GroupId": 1001,
    "Admin": false,
    "Expires": "1900-01-01T00:00:00"
  },
  {
    "Id": 1003,
    "UserId": 20003,
    "GroupId": 1000,
    "Admin": false,
    "Expires": "1900-01-01T00:00:00"
  }
]
...

UPDATE

更新

My final solution was to use the JArray object. A JArray is a JContainer, which is a JToken, which you can add to a JObject. My problem was that I was trying to use a JObject[], which was not a valid JToken

我的最终解决方案是使用 JArray 对象。JArray 是一个 JContainer,它是一个 JToken,您可以将其添加到 JObject。我的问题是我试图使用一个 JObject[],它不是一个有效的 JToken

采纳答案by bruchowski

My final solution was to use the JArrayobject. A JArrayis a JContainer, which is a JToken, which you can add to a JObject. My problem was that I was trying to use a JObject[], which was not a valid JToken

我的最终解决方案是使用该JArray对象。AJArray是 a JContainer,这是 a JToken,您可以将其添加到 a JObject。我的问题是我试图使用 a JObject[],这是无效的JToken

回答by Rob G

Check out the PopulateObject()method, it has a good example of how to do this:

查看PopulateObject()方法,它有一个很好的例子来说明如何做到这一点:

http://james.newtonking.com/projects/json/help/index.html?topic=html/PopulateObject.htm

http://james.newtonking.com/projects/json/help/index.html?topic=html/PopulateObject.htm