如何将 JToken 添加到 JObject? [英] How do you add a JToken to an JObject?

查看:107
本文介绍了如何将 JToken 添加到 JObject?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 JSON.Net 将一些文本中的 JSON 对象添加到现有 JSON 文件中.例如,如果我有如下 JSON 数据:

I'm trying to add a JSON object from some text to an existing JSON file using JSON.Net. For example if I have the JSON data as below:

  {
  "food": {
    "fruit": {
      "apple": {
        "colour": "red",
        "size": "small"
      },
      "orange": {
        "colour": "orange",
        "size": "large"
      }
    }
  }
}

我一直在尝试这样做:

var foodJsonObj = JObject.Parse(jsonText);
var bananaJson = JObject.Parse(@"{ ""banana"" : { ""colour"": ""yellow"", ""size"": ""medium""}}");
var bananaToken = bananaJson as JToken;
foodJsonObj["food"]["fruit"]["orange"].AddAfterSelf(bananaToken);

但这给出了错误:Newtonsoft.Json.Linq.JProperty cannot have multiple values."

我实际上尝试了几种不同的方法,但似乎无处可去.在我的示例中,我真正想做的是将新项目添加到水果"中.请让我知道是否有更好的方法或更简单的库来使用.

I've actually tried a few different ways but can't seem to get anywhere. In my example what I really want to do is add the new item to "fruit". Please let me know if there is a better way of doing this or a simpler library to use.

推荐答案

我想你对 JSON.Net 中什么可以容纳什么感到困惑.

I think you're getting confused about what can hold what in JSON.Net.

  • JToken 是任何类型的 JSON 值的通用表示.它可以是字符串、对象、数组、属性等.
  • JProperty 是与名称配对的单个 JToken 值.只能添加到一个JObject,它的值不能是另一个JProperty.
  • JObjectJProperties 的集合.它不能直接持有任何其他类型的 JToken.
  • A JToken is a generic representation of a JSON value of any kind. It could be a string, object, array, property, etc.
  • A JProperty is a single JToken value paired with a name. It can only be added to a JObject, and its value cannot be another JProperty.
  • A JObject is a collection of JProperties. It cannot hold any other kind of JToken directly.

在您的代码中,您尝试将 JObject(包含香蕉"数据的那个)添加到已经有一个 JProperty(橙色")值(包含 {"colour":"orange","size":"large"}JObject).如您所见,这将导致错误.

In your code, you are attempting to add a JObject (the one containing the "banana" data) to a JProperty ("orange") which already has a value (a JObject containing {"colour":"orange","size":"large"}). As you saw, this will result in an error.

您真正想要做的是将一个名为banana"的JProperty 添加到包含其他水果JPropertiesJObject.这是修改后的代码:

What you really want to do is add a JProperty called "banana" to the JObject which contains the other fruit JProperties. Here is the revised code:

JObject foodJsonObj = JObject.Parse(jsonText);
JObject fruits = foodJsonObj["food"]["fruit"] as JObject;
fruits.Add("banana", JObject.Parse(@"{""colour"":""yellow"",""size"":""medium""}"));

这篇关于如何将 JToken 添加到 JObject?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆