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

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

问题描述

我试图从一些文本添加一个JSON对象使用JSON.Net现有的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"
      }
    }
  }
}

我一直在试图做到这一点是这样的:

I've been trying to do this like this:

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不能有多个值。

其实我已经尝试了几种不同的方法,但似乎无法取得任何进展。在我的例子我真正想要做的就是添加新的项目为果。请让我知道是否有这样做的更好的方式或简单的使用图书馆。

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.


  • A JToken 是任何形式的JSON值的通用表示。这可能是一个字符串,对象,数组,财产等。

  • A JProperty 是一个 JToken使用一个名称配对值。它只能被添加到 JObject ,其价值不能是另一个 JProperty

  • A JObject JProperties 的集合。它不能持有任何其他类型的 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 (橙色 )已经有一个值( 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.

你真的想要做的就是添加一个 JProperty 称为香蕉到 JObject 含有其他水果 JProperties 。下面是修改后的代码:

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天全站免登陆